UNPKG

docxml

Version:

TypeScript (component) library for building and parsing a DOCX file

52 lines (51 loc) 1.78 kB
import fontoxpath from 'fontoxpath'; import { Document as SlimdomDocument, parseXmlDocument, serializeToWellFormedString, } from 'slimdom'; import { evaluateXPathToFirstNode, XQUERY_3_1_LANGUAGE } from './xquery.js'; /** * Serialize an XML node to string using Slimdom's own serializer function, but with the "standard" * typing that Deno has for Node and Document. */ export function serialize(node) { return serializeToWellFormedString(node); } /** * Parse an XML string to DOM using Slimdom's own parser function, but with the "standard" * typing that Deno has for Node and Document -- so that type matching is not complicated further * down the line. */ export function parse(xml) { return parseXmlDocument(xml); } /** * Create a new XML DOM node using XQuery. * * For example: * const el = create(`<derp>{$nerf}</derp>`, { nerf: 'skeet' }); * // Element <derp>skeet</derp> */ export function create(query, variables = {}, asDocument = false) { const node = evaluateXPathToFirstNode(query, null, null, variables, { language: XQUERY_3_1_LANGUAGE, nodesFactory: new SlimdomDocument(), }); if (!node) { throw new Error('Query did not result in a node'); } if (asDocument) { const doc = new SlimdomDocument(); doc.appendChild(node); return doc; } return node; } /** * Run an XQuery Update Facility expression, maybe even repeatedly, which can change an existing DOM. * * Updates by references, returns an empty promise. */ export function update(dom, expression, times = 1) { while (times-- > 0) { fontoxpath.executePendingUpdateList(fontoxpath.evaluateUpdatingExpressionSync(expression, dom, null, {}, { debug: true }) .pendingUpdateList); } }