Replies: 2 comments 3 replies
-
| Thanks! I'm glad you like the library. I think it would be interesting to write a serializer, but it's probably not something I'm going to have time to tackle soon. If I did, though, I would implement it as a separate library (such as |
Beta Was this translation helpful? Give feedback.
-
| For anyone interested, serializing an XmlDocument back to a string is actually pretty straightforward. Here is a serializing function which contains a few deliberate formatting choices and ignores some nodes (comments, CDATA...): export function xmlToString( el: XmlElement | XmlText | XmlComment | XmlDocument, indentationLevel = 0 ) { if (el.constructor.name === 'XmlDocument') return `<?xml version="1.0" encoding="UTF-8"?>${xmlToString( (el as XmlDocument).children[0] )}` if (el.constructor.name === 'XmlText') { const text = (el as XmlText).text const isEmpty = text.replace(/^\s+|\s+$/g, '') === '' if (isEmpty) return '' return text } if (el.constructor.name !== 'XmlElement' || !(el instanceof XmlElement)) return `<!-- unknown -->` const padding = ' '.repeat(indentationLevel) const children = Array.isArray(el.children) ? el.children .map((el) => xmlToString(el, indentationLevel + 1)) .filter((el) => el !== '') .map((elString, index, array) => index < array.length - 1 ? elString.replace(/\n\s*$/g, '') : elString ) .join('') : '' const attrs = Object.keys(el.attributes).reduce( (prev, curr) => prev + ` ${curr}="${el.attributes[curr]}"`, '' ) const parentPadding = ' '.repeat(Math.max(0, indentationLevel - 1)) if (children === '') { return ` ${padding}<${el.name}${attrs}/> ${parentPadding}` } return ` ${padding}<${el.name}${attrs}>${children}</${el.name}> ${parentPadding}` }The function is recursive so you just have to call it on the root XmlDocument to have everything printed out. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi there,
I'm wondering if you would consider adding functionality such that XmlDocument (and perhaps XmlNode) objects could be serialised back to strings of XML.
Thanks for a great library!
Beta Was this translation helpful? Give feedback.
All reactions