lit-xml
Version:
Burning your XML documents to the ground? Yes please. In the mean time, let's use lit-xml.
68 lines • 2.29 kB
JavaScript
import { UnsafeXmlFragment, XmlFragment } from './xml-fragment.js';
import { XMLParser, XMLBuilder } from 'fast-xml-parser';
export function valueToString(value) {
if (value instanceof XmlFragment) {
return value.toStringRaw();
}
if (value instanceof UnsafeXmlFragment) {
return value.toString();
}
if (value === null) {
return 'null';
}
if (value === undefined) {
return '';
}
if (isJsonSerializable(value)) {
return sanitize(value.toJSON());
}
if (Array.isArray(value)) {
return value.map(valueToString).join('');
}
// eslint-disable-next-line
return sanitize(value.toString());
}
function isJsonSerializable(value) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return Boolean(value) && typeof value.toJSON === 'function';
}
const fastXmlOptions = {
attributeNamePrefix: '',
attributesGroupName: '$attr', //default is 'false'
textNodeName: '#text',
ignoreAttributes: false,
removeNSPrefix: false,
allowBooleanAttributes: false,
suppressBooleanAttributes: false,
parseTagValue: true,
parseAttributeValue: false,
trimValues: true,
cdataPropName: '__cdata', //default is 'false'
suppressEmptyNode: true,
};
export function format(xml, { format, indent }) {
if (format) {
const indentBy = new Array(indent).fill(' ').join('');
const xmlAsJson = new XMLParser(fastXmlOptions).parse(xml, fastXmlOptions);
return new XMLBuilder({ ...fastXmlOptions, format, indentBy }).build(xmlAsJson);
}
else {
return xml;
}
}
const XML_ESCAPE_MAP = Object.freeze({ ['&']: '&', ["'"]: ''', ['"']: '"', ['<']: '<', ['>']: '>' });
const XML_SPECIAL_CHAR_REGEX = new RegExp(`([${Object.keys(XML_ESCAPE_MAP).join('')}])`, 'g');
/**
* Escapes XML characters
* " => "
* ' => '
* < => <
* > => >
* & => &
* @see https://stackoverflow.com/questions/1091945/what-characters-do-i-need-to-escape-in-xml-documents#answer-1091953
* @param text the input text to be escaped
*/
export function sanitize(text) {
return text.replace(XML_SPECIAL_CHAR_REGEX, (_match, char) => XML_ESCAPE_MAP[char]);
}
//# sourceMappingURL=xml-helpers.js.map