Nepomuk
Nepomuk

Reputation: 55

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

Given XML

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

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 = xpath.select("/ValCredLookup/ValCredName/@name='valcred-api-cust'", doc);

which works, but if I try

var valcredname = xpath.select("/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 = xpath.select("/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 = xpath.select("/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.

Upvotes: 1

Views: 3173

Answers (1)

har07
har07

Reputation: 89285

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

/ValCredLookup/ValCredName[@name='val-cred-api-cust']/certificate

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 = xpath.select(query, doc);

Upvotes: 3

Related Questions