gpt4 book ai didi

java - 无法解析具有不同命名空间的 XML

转载 作者:行者123 更新时间:2023-12-03 16:53:24 28 4
gpt4 key购买 nike

我有一个这样的示例 XML:

<Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'>
<Header>
</Header>
<Body>
<getNewTokenResponse xmlns="http://abc.examples.com/">
<return>
{{session.key}}
</return>
</getNewTokenResponse>
</Body>
</Envelope>

这段代码用于解析它:
XPath xpath = XPathFactory.newInstance().newXPath();
HashMap nsMap = getNameSpaceMap(input);
xpath.setNamespaceContext(new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
if(nsMap.has(prefix)){
return nsMap.get(prefix);
}
return XMLConstants.NULL_NS_URI;
}

@Override
public String getPrefix(String namespaceURI) {
throw new UnsupportedOperationException("Not supported yet.");
}

@Override
public Iterator getPrefixes(String namespaceURI) {
throw new UnsupportedOperationException("Not supported yet.");
}
});

Node getNewTokenResp =
(Node) xpath.evaluate("/Envelope/Body/getNewTokenResponse/return",
document, XPathConstants.NODE);

由于没有为命名空间使用前缀,它不会返回正确的值。

有没有更好的方法来解析这个?

最佳答案

您应该使用 /s:Envelope/s:Body/p:getNewTokenResponse/p:return作为 XPath 表达式并提供映射 s 的命名空间上下文至http://schemas.xmlsoap.org/soap/envelope/phttp://abc.examples.com/ .

关于java - 无法解析具有不同命名空间的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31922358/

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