UNPKG

@technovilla/x-document

Version:

Javascript implementation of .NET XDocument

48 lines (47 loc) 1.88 kB
"use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var xmldom_1 = require("xmldom"); var x_element_1 = require("./x-element"); var xpath = __importStar(require("xpath")); var exceptions_1 = require("./exceptions"); var xml_formatter_1 = __importDefault(require("xml-formatter")); var XDocument = /** @class */ (function () { function XDocument(doc) { this.doc = doc; var ns = this.doc.documentElement.namespaceURI; this.select = ns ? xpath.useNamespaces({ r: ns }) : xpath.select; } XDocument.parse = function (xml) { var doc = new xmldom_1.DOMParser().parseFromString(xml); return new XDocument(doc); }; XDocument.prototype.xpathSelectElement = function (expression) { var node = this.select(expression, this.doc, true); if (!node) { throw new exceptions_1.ElementNotFound("Element not found. XPath: " + expression); } return new x_element_1.XElement(node); }; XDocument.prototype.toString = function (prettify) { if (prettify === void 0) { prettify = false; } var xml = new xmldom_1.XMLSerializer().serializeToString(this.doc); if (prettify) { return xml_formatter_1.default(xml.replace(/>([\s]+)/gm, '>').replace(/([\s]+)</gm, '<'), { collapseContent: true }); } return xml; }; return XDocument; }()); exports.XDocument = XDocument;