gpt4 book ai didi

Java XML DOM - 如何使用 Element.getAttributeNS

转载 作者:太空宇宙 更新时间:2023-11-04 10:49:24 25 4
gpt4 key购买 nike

我有 XML 节点:

    <soapenv:Body 
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
wsu:Id="Id-223">
....
</soapenv:Body>

我应该将什么值传递给 org.w3c.dom.Element.getAttributeNS(namespaceURI, localName) 来获取属性 Id 的值?

注意我可以使用 Element.getAttribute("wsu:Id") 来获取值,但我必须使用 getAttributeNS 方法

其他信息: org.apache.wss4j.dom.message.token.Timestamp使用以下代码:

public  String getID() {
//WSConstants.WSU_NS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
return element.getAttributeNS(WSConstants.WSU_NS, "Id");
}

我可以确认这段代码不起作用。

[我的代码]是从德米特里的回答中复制的 post 。您可以使用有问题的 XML 和 Dmitry 答案中的 validateSignature 方法轻松重现我的错误

File signatureFile = new File("/home/user1/Downloads/test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(signatureFile);

Node securityNode = doc.getElementsByTagName("wsse:Security").item(0);
Node bodyNode = doc.getElementsByTagName("soap:Body").item(0);
validateSignature(securityNode, bodyNode, key);

然后

public boolean validateSignature(Node signatureNode, Node bodyTag, PublicKey publicKey) {
boolean signatureIsValid = false;
try {
// Create a DOM XMLSignatureFactory that will be used to unmarshal the
// document containing the XMLSignature
String providerName = System.getProperty
("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
(Provider) Class.forName(providerName).newInstance());

// Create a DOMValidateContext and specify a KeyValue KeySelector
// and document context
DOMValidateContext valContext = new DOMValidateContext(new X509KeySelector(publicKey), signatureNode);

String nameSpaceURI = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
org.w3c.dom.Element bodyEle = (Element) bodyTag;
System.out.println(Main.nodeToString(bodyEle));

valContext.setIdAttributeNS((Element) bodyTag, org.apache.ws.security.WSConstants.WSU_NS, "Id");



// Unmarshal the XMLSignature.
XMLSignature signature = fac.unmarshalXMLSignature(valContext);
// Validate the XMLSignature.
signatureIsValid = signature.validate(valContext);

} catch (Exception ex) {
ex.printStackTrace();
}

return signatureIsValid;
}

最佳答案

原来我漏掉了这段代码

dbFactory.setNamespaceAware(true);

关于Java XML DOM - 如何使用 Element.getAttributeNS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48001894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com