Skip to content

Instantly share code, notes, and snippets.

@aabccd021
Last active July 27, 2025 12:42
Show Gist options
  • Save aabccd021/7d7526954780bd084911cee5b24d69bb to your computer and use it in GitHub Desktop.
Save aabccd021/7d7526954780bd084911cee5b24d69bb to your computer and use it in GitHub Desktop.
import * as xpath from 'xpath';
import * as xmldom from '@xmldom/xmldom';
const xml = `<book><title foo="bar">Harry Potter</title></book>`;
const doc = new xmldom.DOMParser().parseFromString(xml, 'text/xml') as any as Node;
const [ firstTitleText ] = xpath.select("//title/text()", doc);
console.assert(firstTitleText.nodeValue === "Harry Potter");
const result: xpath.SelectSingleReturnType = xpath.select1("//title/text()", doc);
console.assert(result.nodeValue === "Harry Potter");
const title = xpath.select1("//title/@foo", doc) as Element;
console.assert(title.nodeValue === "bar");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment