xml-printer
v1.1.3
Published
Converts XML AST structures (like the ones generated by xml-reader) to XML strings
Downloads
422
Maintainers
Readme
xml-printer
Converts XML AST structures (like the ones generated by xml-reader) to XML strings.
It also provides utility functions to escape XML text and attributes.
AST structure
/**
* typedef {Object} XmlNode
* @property {string} name - element name (empty for text nodes)
* @property {string} type - node type ('element' or 'text')
* @property {string} value - value of a text node
* @property {XmlNode} parent - reference to parent node
* @property {Object} attributes - attributes {name: value, ...}
* @property {XmlNode[]} children - array of children nodes
*/
Install
npm install --save xml-printer
Example
import xmlPrint from 'xml-printer';
const ast = {
name: 'greeting',
type: 'element',
value: '',
attributes: {time: '2016-01-02'},
children: [
{
name: '',
type: 'text',
value: 'Hello!',
attributes: {},
children: [],
},
],
};
console.log(xmlPrint(ast));
// <greeting time="2016-01-02">Hello!</greeting>
You can easily generate ASTs from text using xml-reader:
import XmlReader from 'xml-reader';
const ast = XmlReader.parseSync('<greeting time="2016-01-02">Hello!</greeting>');
// returns the AST from the previous example
Options
Pass an options object to the printer function to customize result
import xmlPrint from 'xml-printer';
const ast = { /* see previous example */ };
console.log(xmlPrint(ast, {quote: "'"}));
// <greeting time='2016-01-02'>Hello!</greeting>
Available options
escapeAttributes
: boolean (default:true
) Escapes attributes.escapeText
: boolean (default:true
) Escapes text.selfClose
: boolean (default:true
) Self-close empty elements.quote
: string (default:"
) Quote character, usually"
or'
.
Utilities
This module exports some utility functions which can be useful if you want to escape attributes or text by your own:
escapeXmlText(text: string) => string
import {escapeXmlText} from 'xml-printer';
console.log(escapeXmlText('escape <this>'));
// <![CDATA[escape <this>]]>
escapeXmlAttribute(text: string) => string
import {escapeXmlAttribute} from 'xml-printer';
console.log(escapeXmlAttribute('escape <this>'));
// escape "this"
License
MIT