UNPKG

@openxmldev/linq-to-xml

Version:
65 lines 2.39 kB
/** * @author Thomas Barnekow * @license MIT */ import { DomFactory, DomParser, DomReader, XContainer, XDeclaration, XElement, } from './internal.js'; /** * Represents an XML document. */ export class XDocument extends XContainer { constructor(...contentArray) { super(); this._declaration = null; for (const contentArrayItem of contentArray) { if (contentArrayItem instanceof XDeclaration) { this._declaration = contentArrayItem; } else { this.addContentSkipNotify(contentArrayItem); } } } static load(xmlDocument) { return DomReader.loadXDocument(xmlDocument); } static parse(text) { const [preprocessedText, declaration] = this.preprocess(text); const xmlDocument = DomParser.parseDocument(preprocessedText); const xDocument = XDocument.load(xmlDocument); xDocument.declaration = declaration; return xDocument; } static preprocess(text) { const regex = /^\s*<\?xml\s+version="(?<version>[0-9.]+)"(\s+encoding="(?<encoding>[a-zA-Z0-9-]+)")?(\s+standalone="(?<standalone>yes|no)")?\s*\?>/; const match = text.match(regex); if (!match || !match.groups) return [text, null]; const preprocessedText = text.slice(match[0].length); const declaration = new XDeclaration(match.groups['version'], match.groups['encoding'], match.groups['standalone']); return [preprocessedText, declaration]; } get declaration() { return this._declaration; } set declaration(value) { this._declaration = value; } get root() { const rootNode = this.nodes().firstOrDefault((n) => n instanceof XElement); return rootNode ? rootNode : null; } /** @internal */ cloneNode() { const clone = new XDocument(); clone.declaration = this._declaration !== null ? new XDeclaration(this._declaration.version, this._declaration.encoding, this._declaration.standalone) : null; clone.copyNodes(this); return clone; } toString() { return new XMLSerializer().serializeToString(DomFactory.createDocument(this)); } } //# sourceMappingURL=XDocument.js.map