xpath

DOM 3 XPath 1.0 implemention and helper for JavaScript, with node.js support.

Originally written by Cameron McCormack (blog).

Additional contributions from
Yaron Naveh ({blog}[http://webservices20.blogspot.com/])
goto100
Thomas Weinert
Jimmy Rishe
and others

Install

Install with npm:

npm install xpath

xpath is xml engine agnostic but I recommend to use xmldom:

npm install xmldom

Your first xpath:

““`javascript var xpath = require('xpath') , dom = require('xmldom').DOMParser

var xml = “<book><title>Harry Potter</title></book>” var doc = new dom().parseFromString(xml) var nodes = xpath.select(“//title”, doc)

console.log(nodes.localName + “: ” + nodes.firstChild.data) console.log(“node: ” + nodes.toString()) ““` ➡

title: Harry Potter
Node: <title>Harry Potter</title>

Get text values directly

““`javascript var xml = “<book><title>Harry Potter</title></book>” var doc = new dom().parseFromString(xml) var title = xpath.select(“//title/text()”, doc).toString()

console.log(title) ““` ➡

Harry Potter

Namespaces

““`javascript var xml = “<book><title xmlns='myns'>Harry Potter</title></book>” var doc = new dom().parseFromString(xml) var node = xpath.select(“//*[local-name(.)='title' and namespace-uri(.)='myns']”, doc)

console.log(node.namespaceURI) ““` ➡

myns

Namespaces with easy mappings

““`javascript var xml = “<book xmlns:bookml='example.com/book“});

console.log(select('//bookml:title/text()', doc).nodeValue); ““` ➡

Harry Potter

Default namespace with mapping

““`javascript var xml = “<book xmlns='example.com/book“});

console.log(select('//bookml:title/text()', doc).nodeValue); ““` ➡

Harry Potter

Attributes

““`javascript var xml = “<book author='J. K. Rowling'><title>Harry Potter</title></book>” var doc = new dom().parseFromString(xml) var author = xpath.select1(“/book/@author”, doc).value

console.log(author) ““` ➡

J. K. Rowling