Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
DOM 3 Xpath implemention and helper for node.js
JavaScript
branch: master

This branch is 48 commits ahead, 15 commits behind yaronn:master

Merge pull request #9 from vzvu3k6k/remove-extra-parens

Remove extra closing parentheses in sample codes
latest commit d55179f10b
@goto100 authored
Failed to load latest commit information.
.gitignore merge
README.md Merge pull request #9 from vzvu3k6k/remove-extra-parens
package.json publish
test.js Add unit test for substring-after
xpath.js Fix substring-after()

README.md

xpath

DOM 3 Xpath implemention and helper for node.js.

Originally written by Cameron McCormack (blog).

Thanks to Yaron Naveh (blog).

Install

Install with npm:

npm install xpath

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

npm install xmldom

Your first xpath:

    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[0].localName + ": " + nodes[0].firstChild.data)
    console.log("node: " + nodes[0].toString())

-->

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

Get text values directly

    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

    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)[0]
    console.log(node.namespaceURI)

-->

myns

Namespaces with easy mappings

    var xml = "<book xmlns:bookml='http://example.com/book'><bookml:title>Harry Potter</bookml:title></book>"
    var select = xpath.useNamespaces({"bookml": "http://example.com/book"});
    console.log(select('//bookml:title/text()', doc)[0].nodeValue);

-->

Harry Potter

Default namespace with mapping

    var xml = "<book xmlns='http://example.com/book'><title>Harry Potter</title></book>"
    var select = xpath.useNamespaces({"bookml": "http://example.com/book"});
    console.log(select('//bookml:title/text()', doc)[0].nodeValue);

-->

Harry Potter

Attributes

    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
Something went wrong with that request. Please try again.