MCPcopy Create free account
hub / github.com/NaturalIntelligence/fast-xml-parser / XMLParser

Class XMLParser

src/xmlparser/XMLParser.js:8–77  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6import XmlNode from './xmlNode.js';
7
8export default class XMLParser {
9
10 constructor(options) {
11 this.externalEntities = {};
12 this.options = buildOptions(options);
13
14 }
15 /**
16 * Parse XML dats to JS object
17 * @param {string|Uint8Array} xmlData
18 * @param {boolean|Object} validationOption
19 */
20 parse(xmlData, validationOption) {
21 if (typeof xmlData !== "string" && xmlData.toString) {
22 if (xmlData instanceof Uint8Array &&
23 !(typeof Buffer !== "undefined" && Buffer.isBuffer(xmlData))) {
24 xmlData = new TextDecoder("utf-8", { ignoreBOM: true }).decode(xmlData);
25 } else {
26 xmlData = xmlData.toString();
27 }
28 } else if (typeof xmlData !== "string") {
29 throw new Error("XML data is accepted in String or Bytes[] form.")
30 }
31
32 if (validationOption) {
33 if (validationOption === true) validationOption = {}; //validate with default options
34
35 const result = validate(xmlData, validationOption);
36 if (result !== true) {
37 throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`)
38 }
39 }
40 const orderedObjParser = new OrderedObjParser(this.options, this.externalEntities);
41 // orderedObjParser.entityDecoder.setExternalEntities(this.externalEntities);
42 const orderedResult = orderedObjParser.parseXml(xmlData);
43 if (this.options.preserveOrder || orderedResult === undefined) return orderedResult;
44 else return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher);
45 }
46
47 /**
48 * Add Entity which is not by default supported by this library
49 * @param {string} key
50 * @param {string} value
51 */
52 addEntity(key, value) {
53 if (value.indexOf("&") !== -1) {
54 throw new Error("Entity value can't have '&'")
55 } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) {
56 throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'")
57 } else if (value === "&") {
58 throw new Error("An entity with value '&' is not permitted");
59 } else {
60 this.externalEntities[key] = value;
61 }
62 }
63
64 /**
65 * Returns a Symbol that can be used to access the metadata

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected