Nepomuk Nepomuk - 8 months ago 59
Node.js Question

How do I get by attribute value with xpath in node js

Given XML

<ValCredName name="val-cred-api-cust">
<certificate thumbprint="12345">
<clientID id="1bbfea">

How do I use xpath to get certificate or clientID by attribute value? I have tried things like

doc = new xmldom().parseFromString(data, 'application/xml');
var xpath = require('xpath');
var valcredname ="/ValCredLookup/ValCredName/@name='valcred-api-cust'", doc);

which works, but if I try

var valcredname ="/ValCredLookup/ValCredName/@name='val-cred-api-cust'/certificate", doc);

This doesn't work.

Also how do I reference variables in the xpath

var vcname = 'valcred-api-cust';
var nodes ="/ValCredLookup/ValCredName/@name=????, doc);

What I really need to do is get elements under clientID with an xpath which uses attributes name, thumbprint and id, which are all variables. Like this

var vc = 'val-cred-api-cust';
var tp = '12345';
var id = 1bbfea';
var nodes ="/ValCredLookup/ValCredName/@name=vc/certificate/@thumbprint=tp/clientID/@id=id, doc);

Ok figured out the variable bit

var vc = "'val-cred-api-cust'";

just needed the single quotes in the string, but as far as an xpath statement with multiple attribute values is concerned I don't think that node js xpath can do it.

Answer Source

The correct expression to filter ValCredName by name attribute value, and then return the corresponding certificate element would be :


I don't know if the library that you use provide a better way to access JS variable in XPath. If it doesn't, then you can concatenate JS variable values to construct the XPath expression, for example :

var vc = "val-cred-api-cust";
var query = "/ValCredLookup/ValCredName[@name='" + vc + "']/certificate";
var valcredname =, doc);