XmlParser.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. const sax = require('./sax');
  2. //node types
  3. const NODE = 1;
  4. const TEXT = 2;
  5. const CDATA = 3;
  6. const COMMENT = 4;
  7. const name2type = {
  8. 'NODE': NODE,
  9. 'TEXT': TEXT,
  10. 'CDATA': CDATA,
  11. 'COMMENT': COMMENT,
  12. };
  13. const type2name = {
  14. [NODE]: 'NODE',
  15. [TEXT]: 'TEXT',
  16. [CDATA]: 'CDATA',
  17. [COMMENT]: 'COMMENT',
  18. };
  19. class NodeBase {
  20. wideSelector(selectorString) {
  21. const result = {all: false, before: false, type: 0, name: ''};
  22. if (selectorString === '') {
  23. result.before = true;
  24. } else if (selectorString === '*') {
  25. result.all = true;
  26. } else if (selectorString[0] === '*') {
  27. const typeName = selectorString.substring(1);
  28. result.type = name2type[typeName];
  29. if (!result.type)
  30. throw new Error(`Unknown selector type: ${typeName}`);
  31. } else {
  32. result.name = selectorString;
  33. }
  34. return result;
  35. }
  36. checkNode(rawNode, selectorObj) {
  37. return selectorObj.all || selectorObj.before
  38. || (selectorObj.type && rawNode[0] === selectorObj.type)
  39. || (rawNode[0] === NODE && rawNode[1] === selectorObj.name);
  40. }
  41. findNodeIndex(nodes, selectorObj) {
  42. for (let i = 0; i < nodes.length; i++)
  43. if (this.checkNode(nodes[i], selectorObj))
  44. return i;
  45. }
  46. rawAdd(nodes, rawNode, selectorObj) {
  47. if (selectorObj.all) {
  48. nodes.push(rawNode);
  49. } else if (selectorObj.before) {
  50. nodes.unshift(rawNode);
  51. } else {
  52. const index = this.findNodeIndex(nodes, selectorObj);
  53. if (index >= 0)
  54. nodes.splice(index, 0, rawNode);
  55. else
  56. nodes.push(rawNode);
  57. }
  58. }
  59. rawRemove(nodes, selectorObj) {
  60. if (selectorObj.before)
  61. return;
  62. for (let i = nodes.length - 1; i >= 0; i--) {
  63. if (this.checkNode(nodes[i], selectorObj))
  64. nodes.splice(i, 1);
  65. }
  66. }
  67. }
  68. class NodeObject extends NodeBase {
  69. constructor(raw = null) {
  70. super();
  71. if (raw)
  72. this.raw = raw;
  73. else
  74. this.raw = [];
  75. }
  76. get type() {
  77. return this.raw[0] || null;
  78. }
  79. get name() {
  80. if (this.type === NODE)
  81. return this.raw[1] || null;
  82. return null;
  83. }
  84. set name(value) {
  85. if (this.type === NODE)
  86. this.raw[1] = value;
  87. }
  88. attrs(key, value) {
  89. if (this.type !== NODE)
  90. return null;
  91. let map = null;
  92. if (key instanceof Map) {
  93. map = key;
  94. this.raw[2] = Array.from(map);
  95. } else if (Array.isArray(this.raw[2])) {
  96. map = new Map(this.raw[2]);
  97. if (key) {
  98. map.set(key, value);
  99. this.raw[2] = Array.from(map);
  100. }
  101. }
  102. return map;
  103. }
  104. get value() {
  105. switch (this.type) {
  106. case NODE:
  107. return this.raw[3] || null;
  108. case TEXT:
  109. case CDATA:
  110. case COMMENT:
  111. return this.raw[1] || null;
  112. }
  113. return null;
  114. }
  115. set value(v) {
  116. switch (this.type) {
  117. case NODE:
  118. this.raw[3] = v;
  119. break;
  120. case TEXT:
  121. case CDATA:
  122. case COMMENT:
  123. this.raw[1] = v;
  124. }
  125. }
  126. add(node, after = '*') {
  127. if (this.type !== NODE)
  128. return;
  129. const selectorObj = this.wideSelector(after);
  130. if (!Array.isArray(this.raw[3]))
  131. this.raw[3] = [];
  132. if (Array.isArray(node)) {
  133. for (const node_ of node)
  134. this.rawAdd(this.raw[3], node_.raw, selectorObj);
  135. } else {
  136. this.rawAdd(this.raw[3], node.raw, selectorObj);
  137. }
  138. return this;
  139. }
  140. remove(selector = '') {
  141. if (this.type !== NODE || !this.raw[3])
  142. return;
  143. const selectorObj = this.wideSelector(selector);
  144. this.rawRemove(this.raw[3], selectorObj);
  145. if (!this.raw[3].length)
  146. this.raw[3] = null;
  147. return this;
  148. }
  149. each(callback) {
  150. if (this.type !== NODE || !this.raw[3])
  151. return;
  152. for (const n of this.raw[3]) {
  153. if (callback(new NodeObject(n)) === false)
  154. break;
  155. }
  156. return this;
  157. }
  158. eachDeep(callback) {
  159. if (this.type !== NODE || !this.raw[3])
  160. return;
  161. const deep = (nodes, route = '') => {
  162. for (const n of nodes) {
  163. const node = new NodeObject(n);
  164. if (callback(node, route) === false)
  165. return false;
  166. if (node.type === NODE && node.value) {
  167. if (deep(node.value, `${route}${route ? '/' : ''}${node.name}`) === false)
  168. return false;
  169. }
  170. }
  171. }
  172. deep(this.raw[3]);
  173. return this;
  174. }
  175. }
  176. class XmlParser extends NodeBase {
  177. constructor(rawNodes = []) {
  178. super();
  179. this.NODE = NODE;
  180. this.TEXT = TEXT;
  181. this.CDATA = CDATA;
  182. this.COMMENT = COMMENT;
  183. this.rawNodes = rawNodes;
  184. }
  185. get count() {
  186. return this.rawNodes.length;
  187. }
  188. get nodes() {
  189. const result = [];
  190. for (const n of this.rawNodes)
  191. result.push(new NodeObject(n));
  192. return result;
  193. }
  194. nodeObject(node) {
  195. return new NodeObject(node);
  196. }
  197. newParser(nodes) {
  198. return new XmlParser(nodes);
  199. }
  200. checkType(type) {
  201. if (!type2name[type])
  202. throw new Error(`Invalid type: ${type}`);
  203. }
  204. createTypedNode(type, nameOrValue, attrs = null, value = null) {
  205. this.checkType(type);
  206. switch (type) {
  207. case NODE:
  208. if (!nameOrValue || typeof(nameOrValue) !== 'string')
  209. throw new Error('Node name must be non-empty string');
  210. return new NodeObject([type, nameOrValue, attrs, value]);
  211. case TEXT:
  212. case CDATA:
  213. case COMMENT:
  214. if (typeof(nameOrValue) !== 'string')
  215. throw new Error('Node value must be of type string');
  216. return new NodeObject([type, nameOrValue]);
  217. }
  218. }
  219. createNode(name, attrs = null, value = null) {
  220. return this.createTypedNode(NODE, name, attrs, value);
  221. }
  222. createText(value = null) {
  223. return this.createTypedNode(TEXT, value);
  224. }
  225. createCdata(value = null) {
  226. return this.createTypedNode(CDATA, value);
  227. }
  228. createComment(value = null) {
  229. return this.createTypedNode(COMMENT, value);
  230. }
  231. add(node, after = '*') {
  232. const selectorObj = this.wideSelector(after);
  233. for (const n of this.rawNodes) {
  234. if (n && n[0] === NODE) {
  235. if (!Array.isArray(n[3]))
  236. n[3] = [];
  237. if (Array.isArray(node)) {
  238. for (const node_ of node)
  239. this.rawAdd(n[3], node_.raw, selectorObj);
  240. } else {
  241. this.rawAdd(n[3], node.raw, selectorObj);
  242. }
  243. }
  244. }
  245. return this;
  246. }
  247. addRoot(node, after = '*') {
  248. const selectorObj = this.wideSelector(after);
  249. if (Array.isArray(node)) {
  250. for (const node_ of node)
  251. this.rawAdd(this.rawNodes, node_.raw, selectorObj);
  252. } else {
  253. this.rawAdd(this.rawNodes, node.raw, selectorObj);
  254. }
  255. return this;
  256. }
  257. remove(selector = '') {
  258. const selectorObj = this.wideSelector(selector);
  259. for (const n of this.rawNodes) {
  260. if (n && n[0] === NODE && Array.isArray(n[3])) {
  261. this.rawRemove(n[3], selectorObj);
  262. if (!n[3].length)
  263. n[3] = null;
  264. }
  265. }
  266. return this;
  267. }
  268. removeRoot(selector = '') {
  269. const selectorObj = this.wideSelector(selector);
  270. this.rawRemove(this.rawNodes, selectorObj);
  271. return this;
  272. }
  273. each(callback, self = false) {
  274. if (self) {
  275. for (const n of this.rawNodes) {
  276. if (callback(new NodeObject(n)) === false)
  277. return this;
  278. }
  279. } else {
  280. for (const n of this.rawNodes) {
  281. if (n[0] === NODE && n[3]) {
  282. for (const nn of n[3])
  283. if (callback(new NodeObject(nn)) === false)
  284. return this;
  285. }
  286. }
  287. }
  288. return this;
  289. }
  290. eachSelf(callback) {
  291. return this.each(callback, true);
  292. }
  293. eachDeep(callback, self = false) {
  294. const deep = (nodes, route = '') => {
  295. for (const n of nodes) {
  296. const node = new NodeObject(n);
  297. if (callback(node, route) === false)
  298. return false;
  299. if (node.type === NODE && node.value) {
  300. if (deep(node.value, `${route}${route ? '/' : ''}${node.name}`) === false)
  301. return false;
  302. }
  303. }
  304. }
  305. if (self) {
  306. deep(this.rawNodes);
  307. } else {
  308. for (const n of this.rawNodes) {
  309. if (n[0] === NODE && n[3])
  310. if (deep(n[3]) === false)
  311. break;
  312. }
  313. }
  314. return this;
  315. }
  316. eachDeepSelf(callback) {
  317. return this.eachDeep(callback, true);
  318. }
  319. rawSelect(nodes, selectorObj, callback) {
  320. for (const n of nodes)
  321. if (this.checkNode(n, selectorObj))
  322. callback(n);
  323. return this;
  324. }
  325. select(selector = '', self = false) {
  326. let newRawNodes = [];
  327. if (selector.indexOf('/') >= 0) {
  328. const selectors = selector.split('/');
  329. let res = this;
  330. for (const sel of selectors) {
  331. res = res.select(sel, self);
  332. self = false;
  333. }
  334. newRawNodes = res.rawNodes;
  335. } else {
  336. const selectorObj = this.wideSelector(selector);
  337. if (self) {
  338. this.rawSelect(this.rawNodes, selectorObj, (node) => {
  339. newRawNodes.push(node);
  340. })
  341. } else {
  342. for (const n of this.rawNodes) {
  343. if (n && n[0] === NODE && Array.isArray(n[3])) {
  344. this.rawSelect(n[3], selectorObj, (node) => {
  345. newRawNodes.push(node);
  346. })
  347. }
  348. }
  349. }
  350. }
  351. return new XmlParser(newRawNodes);
  352. }
  353. selectSelf(selector) {
  354. return this.select(selector, true);
  355. }
  356. selectFirst(selector, self) {
  357. const result = this.select(selector, self);
  358. const node = (result.count ? result.rawNodes[0] : null);
  359. return new NodeObject(node);
  360. }
  361. selectFirstSelf(selector) {
  362. return this.selectFirst(selector, true);
  363. }
  364. toJson(options = {}) {
  365. const {format = false} = options;
  366. if (format)
  367. return JSON.stringify(this.rawNodes, null, 2);
  368. else
  369. return JSON.stringify(this.rawNodes);
  370. }
  371. fromJson(jsonString) {
  372. const parsed = JSON.parse(jsonString);
  373. if (!Array.isArray(parsed))
  374. throw new Error('JSON parse error: root element must be array');
  375. this.rawNodes = parsed;
  376. return this;
  377. }
  378. toString(options = {}) {
  379. const {
  380. encoding = 'utf-8',
  381. format = false,
  382. noHeader = false,
  383. expandEmpty = false
  384. } = options;
  385. let deepType = 0;
  386. let out = '';
  387. if (!noHeader)
  388. out += `<?xml version="1.0" encoding="${encoding}"?>`;
  389. const nodesToString = (nodes, depth = 0) => {
  390. let result = '';
  391. const indent = '\n' + ' '.repeat(depth);
  392. let lastType = 0;
  393. for (const n of nodes) {
  394. const node = new NodeObject(n);
  395. let open = '';
  396. let body = '';
  397. let close = '';
  398. if (node.type === NODE) {
  399. if (!node.name)
  400. continue;
  401. let attrs = '';
  402. const nodeAttrs = node.attrs();
  403. if (nodeAttrs) {
  404. for (const [attrName, attrValue] of nodeAttrs) {
  405. if (typeof(attrValue) === 'string')
  406. attrs += ` ${attrName}="${attrValue}"`;
  407. else
  408. if (attrValue)
  409. attrs += ` ${attrName}`;
  410. }
  411. }
  412. if (node.value)
  413. body = nodesToString(node.value, depth + 2);
  414. if (!body && !expandEmpty) {
  415. open = (format && lastType !== TEXT ? indent : '');
  416. open += `<${node.name}${attrs}/>`;
  417. } else {
  418. open = (format && lastType !== TEXT ? indent : '');
  419. open += `<${node.name}${attrs}>`;
  420. close = (format && deepType && deepType !== TEXT ? indent : '');
  421. close += `</${node.name}>`;
  422. }
  423. } else if (node.type === TEXT) {
  424. body = node.value || '';
  425. } else if (node.type === CDATA) {
  426. body = (format && lastType !== TEXT ? indent : '');
  427. body += `<![CDATA[${node.value || ''}]]>`;
  428. } else if (node.type === COMMENT) {
  429. body = (format && lastType !== TEXT ? indent : '');
  430. body += `<!--${node.value || ''}-->`;
  431. }
  432. result += `${open}${body}${close}`;
  433. lastType = node.type;
  434. }
  435. deepType = lastType;
  436. return result;
  437. }
  438. out += nodesToString(this.rawNodes) + (format ? '\n' : '');
  439. return out;
  440. }
  441. fromString(xmlString, options = {}) {
  442. const {
  443. lowerCase = false,
  444. whiteSpace = false,
  445. pickNode = false,
  446. } = options;
  447. const parsed = [];
  448. const root = this.createNode('root', null, parsed);//fake node
  449. let node = root;
  450. let route = '';
  451. let routeStack = [];
  452. let ignoreNode = false;
  453. const onStartNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  454. if (tag == '?xml')
  455. return;
  456. if (!ignoreNode && pickNode) {
  457. route += `${route ? '/' : ''}${tag}`;
  458. ignoreNode = !pickNode(route);
  459. }
  460. let newNode = node;
  461. if (!ignoreNode)
  462. newNode = this.createNode(tag);
  463. routeStack.push({tag, route, ignoreNode, node: newNode});
  464. if (ignoreNode)
  465. return;
  466. if (tail && tail.trim() !== '') {
  467. const parsedAttrs = sax.getAttrsSync(tail, lowerCase);
  468. const attrs = new Map();
  469. for (const attr of parsedAttrs.values()) {
  470. attrs.set(attr.fn, attr.value);
  471. }
  472. if (attrs.size)
  473. newNode.attrs(attrs);
  474. }
  475. if (!node.value)
  476. node.value = [];
  477. node.value.push(newNode.raw);
  478. node = newNode;
  479. };
  480. const onEndNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  481. if (routeStack.length && routeStack[routeStack.length - 1].tag === tag) {
  482. routeStack.pop();
  483. if (routeStack.length) {
  484. const last = routeStack[routeStack.length - 1];
  485. route = last.route;
  486. ignoreNode = last.ignoreNode;
  487. node = last.node;
  488. } else {
  489. route = '';
  490. ignoreNode = false;
  491. node = root;
  492. }
  493. }
  494. }
  495. const onTextNode = (text, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  496. if (ignoreNode || (pickNode && !pickNode(`${route}/*TEXT`)))
  497. return;
  498. if (!whiteSpace && text.trim() == '')
  499. return;
  500. if (!node.value)
  501. node.value = [];
  502. node.value.push(this.createText(text).raw);
  503. };
  504. const onCdata = (tagData, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  505. if (ignoreNode || (pickNode && !pickNode(`${route}/*CDATA`)))
  506. return;
  507. if (!node.value)
  508. node.value = [];
  509. node.value.push(this.createCdata(tagData).raw);
  510. }
  511. const onComment = (tagData, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  512. if (ignoreNode || (pickNode && !pickNode(`${route}/*COMMENT`)))
  513. return;
  514. if (!node.value)
  515. node.value = [];
  516. node.value.push(this.createComment(tagData).raw);
  517. }
  518. sax.parseSync(xmlString, {
  519. onStartNode, onEndNode, onTextNode, onCdata, onComment, lowerCase
  520. });
  521. this.rawNodes = parsed;
  522. return this;
  523. }
  524. toObject(options = {}) {
  525. const {
  526. compactText = false
  527. } = options;
  528. const nodesToObject = (nodes) => {
  529. const result = {};
  530. for (const n of nodes) {
  531. const node = new NodeObject(n);
  532. if (node.type === NODE) {
  533. if (!node.name)
  534. continue;
  535. let newNode = {};
  536. const nodeAttrs = node.attrs();
  537. if (nodeAttrs)
  538. newNode['*ATTRS'] = Object.fromEntries(nodeAttrs);
  539. if (node.value) {
  540. Object.assign(newNode, nodesToObject(node.value));
  541. //схлопывание текстового узла до string
  542. if (compactText
  543. && !Array.isArray(newNode)
  544. && Object.prototype.hasOwnProperty.call(newNode, '*TEXT')
  545. && Object.keys(newNode).length === 1) {
  546. newNode = newNode['*TEXT'];
  547. }
  548. }
  549. if (!Object.prototype.hasOwnProperty.call(result, node.name)) {
  550. result[node.name] = newNode;
  551. } else {
  552. if (!Array.isArray(result[node.name])) {
  553. result[node.name] = [result[node.name]];
  554. }
  555. result[node.name].push(newNode);
  556. }
  557. } else if (node.type === TEXT) {
  558. if (!result['*TEXT'])
  559. result['*TEXT'] = '';
  560. result['*TEXT'] += node.value || '';
  561. } else if (node.type === CDATA) {
  562. if (!result['*CDATA'])
  563. result['*CDATA'] = '';
  564. result['*CDATA'] += node.value || '';
  565. } else if (node.type === COMMENT) {
  566. if (!result['*COMMENT'])
  567. result['*COMMENT'] = '';
  568. result['*COMMENT'] += node.value || '';
  569. }
  570. }
  571. return result;
  572. }
  573. return nodesToObject(this.rawNodes);
  574. }
  575. fromObject(xmlObject) {
  576. const objectToNodes = (obj) => {
  577. const result = [];
  578. for (const [tag, objNode] of Object.entries(obj)) {
  579. if (tag === '*TEXT') {
  580. result.push(this.createText(objNode).raw);
  581. } else if (tag === '*CDATA') {
  582. result.push(this.createCdata(objNode).raw);
  583. } else if (tag === '*COMMENT') {
  584. result.push(this.createComment(objNode).raw);
  585. } else if (tag === '*ATTRS') {
  586. //пропускаем
  587. } else {
  588. if (typeof(objNode) === 'string' || typeof(objNode) === 'number') {
  589. result.push(this.createNode(tag, null, [this.createText(objNode.toString()).raw]).raw);
  590. } else if (Array.isArray(objNode)) {
  591. for (const n of objNode) {
  592. if (typeof(n) === 'string') {
  593. result.push(this.createNode(tag, null, [this.createText(n).raw]).raw);
  594. } else if (typeof(n) === 'object') {
  595. result.push(this.createNode(tag, (n['*ATTRS'] ? Object.entries(n['*ATTRS']) : null), objectToNodes(n)).raw);
  596. }
  597. }
  598. } else if (typeof(objNode) === 'object') {
  599. result.push(this.createNode(tag, (objNode['*ATTRS'] ? Object.entries(objNode['*ATTRS']) : null), objectToNodes(objNode)).raw);
  600. } else {
  601. throw new Error(`Unknown node type "${typeof(objNode)}" of node: ${objNode}`);
  602. }
  603. }
  604. }
  605. return result;
  606. };
  607. this.rawNodes = objectToNodes(xmlObject);
  608. return this;
  609. }
  610. // XML Inspector start
  611. narrowSelector(selector) {
  612. const result = [];
  613. selector = selector.trim();
  614. //последний индекс не учитывется, только если не задан явно
  615. if (selector && selector[selector.length - 1] == ']')
  616. selector += '/';
  617. const levels = selector.split('/');
  618. for (const level of levels) {
  619. const [name, indexPart] = level.split('[');
  620. let index = 0;
  621. if (indexPart) {
  622. const i = indexPart.indexOf(']');
  623. index = parseInt(indexPart.substring(0, i), 10) || 0;
  624. }
  625. let type = NODE;
  626. if (name[0] === '*') {
  627. const typeName = name.substring(1);
  628. type = name2type[typeName];
  629. if (!type)
  630. throw new Error(`Unknown selector type: ${typeName}`);
  631. }
  632. result.push({type, name, index});
  633. }
  634. if (result.length);
  635. result[result.length - 1].last = true;
  636. return result;
  637. }
  638. inspect(selector = '') {
  639. selector = this.narrowSelector(selector);
  640. let raw = this.rawNodes;
  641. for (const s of selector) {
  642. if (s.name) {
  643. let found = [];
  644. for (const n of raw) {
  645. if (n[0] === s.type && (n[0] !== NODE || s.name === '*NODE' || n[1] === s.name)) {
  646. found.push(n);
  647. if (found.length > s.index && !s.last)
  648. break;
  649. }
  650. }
  651. raw = found;
  652. }
  653. if (raw.length && !s.last) {
  654. if (s.index < raw.length) {
  655. raw = raw[s.index];
  656. if (raw[0] === NODE && raw[3])
  657. raw = raw[3];
  658. else {
  659. raw = [];
  660. break;
  661. }
  662. } else {
  663. raw = [];
  664. break;
  665. }
  666. }
  667. }
  668. return new XmlParser(raw);
  669. }
  670. $$(selector) {
  671. return this.inspect(selector);
  672. }
  673. $$array(selector) {
  674. const res = this.inspect(selector);
  675. const result = [];
  676. for (const n of res.rawNodes)
  677. if (n[0] === NODE)
  678. result.push(new XmlParser([n]));
  679. return result;
  680. }
  681. $(selector) {
  682. const res = this.inspect(selector);
  683. const node = (res.count ? res.rawNodes[0] : null);
  684. return new NodeObject(node);
  685. }
  686. v(selector = '') {
  687. const res = this.$(selector);
  688. return (res.type ? res.value : null);
  689. }
  690. text(selector = '') {
  691. const res = this.$(`${selector}/*TEXT`);
  692. return (res.type === TEXT ? res.value : null);
  693. }
  694. comment(selector = '') {
  695. const res = this.$(`${selector}/*COMMENT`);
  696. return (res.type === COMMENT ? res.value : null);
  697. }
  698. cdata(selector = '') {
  699. const res = this.$(`${selector}/*CDATA`);
  700. return (res.type === CDATA ? res.value : null);
  701. }
  702. concat(selector = '') {
  703. const res = this.$$(selector);
  704. const out = [];
  705. for (const n of res.rawNodes) {
  706. const node = new NodeObject(n);
  707. if (node.type && node.type !== NODE)
  708. out.push(node.value);
  709. }
  710. return (out.length ? out.join('') : null);
  711. }
  712. attrs(selector = '') {
  713. const res = this.$(selector);
  714. const attrs = res.attrs();
  715. return (res.type === NODE && attrs ? Object.fromEntries(attrs) : null);
  716. }
  717. // XML Inspector finish
  718. }
  719. module.exports = XmlParser;