Some XML helpers to help with OOXML development
npm install @ooxml-tools/xml
Some XML helpers to help with OOXML development
> [!NOTE]
> These are all based around xml-js and output that modules internal format
When working with xml-js it's really handy to not have to worry about when you're passing an XML string our the xml-js JSON type called Element
This helper function just outputs an Element for either input
``ts`
asXmlElement("
asXmlElement({ name: "name", text: "foo" }); // => {name: "name", text: "foo"}
> [!NOTE]
> All the other functions in this document that accept XML, also accept this Element (using this function)
An XML tagged template literal with the following features
- error if XML is incorrect
- array support in substitution
The following will error in development, because of mismatched start/end tags
`ts
safeXml;`
Substitution of arrays "just works" so you can map values in the tagged template literals
`ts
const items = [1, 2, 3].map((n) => safeXml);
const outXml = safeXml;
assert.equal(
outXml,
,`
);
This also makes it easy to support
Removes non required whitespace from the XML
`ts
const outXml = compact(
something
);`
assert.equal(outXml, "
For XML to be valid, there must be a single root node. When composing apps it's handy for that not to be true.
For example the following would error
`ts
const xml = safeXml
;`
So instead we'd like something like a HTML fragment
`ts
const xml = safeXml
;`
So we did just that, collapseFragments walks over a tree removing nodes.
`ts
const innerBit = safeXml
;
const newXml = collapseFragments(
safeXml
${innerBit}
,
);
assert.equal(
newXml,
,`
);
From the wikipedia page
> CDATA section is a piece of element content that is marked up to be interpreted literally, as textual data, not as marked-up content.
But is ugly and hard to read, so instead
`ts
safeXml;`
Format XML in a consistent way, useful for logging and snapshot testing
`ts
format(
); /* =>`
*
* one
*
*/
`ts
const element = getAllByTestId(
Hello
)`
`ts
const element = getByTestId(
Hello
)`
`ts
getSingleTextNode() // => {type: "text", text: "hello world"}`
Else throws an error
`ts
getSingleTextNode() // => throws Error`
`ts
const element = removeTestIds(
Hello
) /* =>``
*
*
* Hello
*
*
*/

MIT