XPath查询带有命名空间的根元素。

3

我试图用命名空间来访问根元素,并提供对库xml-crypto的引用。

我没有正确给出路径,请指导。目标是对文档进行签名,以便在标记<samlp:Response之后插入签名。

<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="efedb3b0-909f-4b39-b8c0-57427ee8dc83" Version="2.0" IssueInstant="2019-11-08T15:34:51.272Z">

    <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">http://www.example.com</saml:Issuer>

</samlp:Response>

nodeJS 代码

var SignedXml = require('xml-crypto').SignedXml, fs = require('fs');
var sig = new SignedXml();

sig.addReference("//*[local-name(.)='samlp:Response']");

sig.signingKey = fs.readFileSync(__dirname + "/client.pem");
sig.computeSignature(xml);
fs.writeFileSync(__dirname + "/signed.xml", sig.getSignedXml());

尝试

sig.addReference("//samlp:Response");

错误:无法解析QName samlp

但在https://www.freeformatter.com/xpath-tester.html运行良好。

1个回答

2
如果您希望打败/绕过命名空间,则更改:
sig.addReference("//*[local-name(.)='samlp:Response']");

to

sig.addReference("//*[local-name()='Response']");

因为命名空间前缀samlp不是本地名称Response的一部分。
有关XPath中命名空间的全面答案,请参见How does XPath deal with XML namespaces?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接