I want use xmldom + xpath in typescript. For xpath package are none type. So I installed package xpath-ts + xmldom-ts.
But the examples on package documentation not working.
example:
import { DOMParserImpl as dom } from 'xmldom-ts';
import * as xpath from 'xpath-ts';
const xml = '<book><title>Harry Potter</title></book>';
const doc = new dom().parseFromString(xml);
const nodes = xpath.select('//title', doc);
console.log(nodes[0].localName + ': ' + nodes[0].firstChild.data);
console.log('Node: ' + nodes[0].toString());
on execution I got the error:
src/importDWD.ts:100:43 - error TS2345: Argument of type 'Document' is not assignable to parameter of type 'Node'.
Type 'Document' is missing the following properties from type 'Node': observers, addObserver, delObserver
100 const nodes = xpath.select('//title', doc);
~~~
and a lot of other compile errors
How can I use xpath in typescript?
Install xmldom package + types and the xpath-ts package
npm install --save-dev @types/xmldom
Now you can find a XML node by xpath expression:
let xml: string = '<book><title>Harry Potter</title></book>';
const parser = new xmldom.DOMParser()
let doc: Document = parser.parseFromString(xml)
let nodes: Node[] = xpath.select('//title',doc) as Node[]
console.log(nodes[0].nodeName + ': ' + nodes[0].firstChild.nodeValue);
console.log('Node: ' + nodes[0].toString());
output
title: Harry Potter
Node: <title>Harry Potter</title>
and the evaluate function
let xml: string = '<book><title>Harry Potter</title></book>';
const parser = new xmldom.DOMParser()
let doc: Document = parser.parseFromString(xml)
let result: XPathResult = xpath.evaluate("/book/title",
doc, null, xpath.XPathResult.ANY_TYPE, null)
let node = result.iterateNext();
while (node) {
console.log(node.nodeName + ': ' + node.firstChild.nodeValue);
console.log('Node: ' + node.toString());
node = result.iterateNext();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.