SHARE
TWEET

Untitled

a guest Jul 22nd, 2019 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Document, Element, parseXml } from 'libxmljs';
  2. import { VError } from 'verror';
  3.  
  4. export class XMLReader {
  5.   private document: Document;
  6.   private namespaces: Record<string, string>;
  7.  
  8.   constructor(inputXml: string) {
  9.     try {
  10.       this.document = parseXml(inputXml);
  11.       this.namespaces = {};
  12.  
  13.       // Bad typings? No .namespaces()
  14.       for (const ns of (this.document as any).namespaces()) {
  15.         let name = ns.prefix();
  16.         if (name === null) {
  17.           name = '_';
  18.         }
  19.         this.namespaces[name] = ns.href();
  20.       }
  21.     } catch (cause) {
  22.       throw new VError(
  23.         { cause, name: 'ParseError', info: { inputXml } },
  24.         'Failed to parse XML',
  25.       );
  26.     }
  27.   }
  28.  
  29.   public get(xpath: string): string {
  30.     const element: Element | null = this.document.get(xpath, this.namespaces);
  31.  
  32.     if (element === null || element === undefined) {
  33.       throw new Error(`XPath element "${xpath}" was not found`);
  34.     }
  35.  
  36.     return element.text();
  37.   }
  38. }
  39.  
  40. const input: string = `<?xml version="1.0" encoding="UTF-8"?>
  41.   <root xmlns="default:namespace" xmlns:opt="inner:namespace">
  42.     <outer><opt:inner>value</opt:inner></outer>
  43.   </root>
  44.   `;
  45.  
  46. const xml = new XMLReader(input);
  47.  
  48. // Need to specify the default namespace with _.
  49. console.log(xml.get('/_:root/_:outer/opt:inner'));
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top