给定XML
<ValCredLookup>
<ValCredName name="val-cred-api-cust">
<certificate thumbprint="12345">
<clientID id="1bbfea">
<Merchant-id>123456789</Merchant-id>
</clientID>
</certificate>
</ValCredName>
</ValCredLookup>
如何使用xpath按属性值获取证书或clientID?我尝试过像
这样的事情doc = new xmldom().parseFromString(data, 'application/xml');
var xpath = require('xpath');
var valcredname = xpath.select("/ValCredLookup/ValCredName/@name='valcred-api-cust'", doc);
有效,但如果我尝试
var valcredname = xpath.select("/ValCredLookup/ValCredName/@name='val-cred-api-cust'/certificate", doc);
这不起作用。
另外如何引用xpath中的变量
var vcname = 'valcred-api-cust';
var nodes = xpath.select("/ValCredLookup/ValCredName/@name=????, doc);
我真正需要做的是使用xpath获取clientID下的元素,该xpath使用属性name,thumbprint和id,它们都是变量。喜欢这个
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);
好的找出了变量位
var vc = "'val-cred-api-cust'";
只需要字符串中的单引号,但就具有多个属性值的xpath语句而言,我不认为节点js xpath可以做到。
答案 0 :(得分:2)
通过ValCredName
属性值过滤name
,然后返回相应的certificate
元素的正确表达式将是:
/ValCredLookup/ValCredName[@name='val-cred-api-cust']/certificate
我不知道您使用的库是否提供了更好的方法来访问XPath中的JS变量。如果没有,那么您可以连接JS变量值来构造XPath表达式,例如:
var vc = "val-cred-api-cust";
var query = "/ValCredLookup/ValCredName[@name='" + vc + "']/certificate";
var valcredname = xpath.select(query, doc);