Skip to content

XMLPrinter

do- edited this page Oct 3, 2024 · 42 revisions

XMLPrinter is a utility class for generating well formed XML text using a minimalistic low level API.

Depending on the space option, the output can be:

  • either onelined (when space is undefined)
  • or pretty printed, with each nesting level indented with the space string (\t for instance) or space number of 0x20 characters.

For pretty printing, os.EOL is used as the default line ending. It's overridable with the eponymous option.

By default, attributes are printed inside the containing opening tags without any breaks, but you can set the additional attrSpace: in this case, each attribute is presented on a new line.

For the sake of readability, all \n and \r characters are replaced with numerical entities for both character nodes and attribute values. Though it's possible to turn off this feature with the encodeLineBreaks option.

XML comments are not supported by the API, neither are DTDs nor PIs (but the XML declaration).

Constructor

const xp = new XMLPrinter ({
//  space: 2, 
//  attrSpace: 1, 
//  EOL: '\n',
//  level: 0, 
//  encodeLineBreaks: false,
})

Options

Name Default Description
attrSpace undefined The additional indent for attributes. Similarly to space, can be set as a string or a number. When set, a line is added for each attribute. Otherwise, each opening tag belong to one line
encodeLineBreaks true Whether to print line breaking characters as nuberical entities
space undefined A literal string or the number of space (0x20) characters to indent opening and closing tags
level 0 The additional indent level for each string
EOL undefined os.EOL by default, this value is used for line breaks

Methods

Low Level API

Hereafter, the methods are listed in typical calling order, not alphabetically.

writeXMLDecl (encoding?, standalone?)

Prints <?xml version="1.0" ... ?> with encoding and standalone` (when set). Throws an error unless called not first.

openElement (name)

Prints <${name} prepended with the necessary whitespace leaving the tag opened for appending attributes.

writeAttribute (name, value)

Prints ${name}="${value}" with the needed spacing and character escaping. Both name, value must be given as strings. Throws an error unless an opening tag is still pending.

writeCharacters (value)

For a zero length value, does nothing.

Otherwise, closes the opening tag (if not yet) and prints the escaped value. Throws an error when called before opening of after closing the root element.

closeElement ()

Prints the indented </${name}> (with the name taken out from the internal stack) or just />.

Convenience Methods

writeNode (node)

Prints out a complete XMLNode, recursively.

Clone this wiki locally