gpt4 book ai didi

java - 使用 XPath 和 XML XPath Api 获取 Soap Body

转载 作者:行者123 更新时间:2023-11-29 03:29:10 25 4
gpt4 key购买 nike

我在我的应用程序中使用 XML XPath API

这是我的 SOAP 请求

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tes="http://testwork/">
<soapenv:Header/>
<soapenv:Body>
<tes:sayHelloWorldFrom>
<!--Optional:-->
<arg0>value</arg0>
</tes:sayHelloWorldFrom>
</soapenv:Body>
</soapenv:Envelope>

我想从这条消息中检索正文,因此我想要

<soapenv:Body>
<tes:sayHelloWorldFrom>
<!--Optional:-->
<arg0>value</arg0>
</tes:sayHelloWorldFrom>
</soapenv:Body>

我的一段代码看起来像

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
org.w3c.dom.Document doc = null;
try {
doc = factory.newDocumentBuilder().parse(is);
XPathFactory xFactory = XPathFactory.newInstance();
XPath xPath = xFactory.newXPath();
Object result = xPath.compile("/soapenv:Envelope/soapenv:Body").evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
log.info("result " + nodes);

但结果是 result com.sun.org.apache.xml.internal.dtm.ref.DTMNodeList@19f76837

那我做错了什么?

最佳答案

XPathConstants.NODESET 指示 API 返回它找到的与查询匹配的结果的 NodeList

当您期望匹配数量可变时,这很有用。您可以遍历列表...

for (int index = 0; index < nodes.getLength(); index++) {
Node node = nodes.item(index);
//...
}

如果您确信您只会收到一个结果(或者您只想要第一个匹配项),您可以改用 XPathConstants.NODE

Object result = xPath.compile("/soapenv:Envelope/soapenv:Body").evaluate(doc, XPathConstants.NODE);
Node node = (Node)result;

已更新

如果不执行以下操作,可能无法做到这一点,但 namespace 让我头疼......

创建工厂后,将其 namespace 感知设置为false`,然后从搜索中删除节点 namespace 上下文,例如...

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
org.w3c.dom.Document doc = null;
try {
doc = factory.newDocumentBuilder().parse(new File("Soap.xml"));

XPathFactory xFactory = XPathFactory.newInstance();
XPath xPath = xFactory.newXPath();
Object result = xPath.compile("/Envelope/Body").evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println("Found " + nodes.getLength() + " matches");
for (int index = 0; index < nodes.getLength(); index++) {
Node node = nodes.item(index);
System.out.println(node);
}
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException exp) {
exp.printStackTrace();
}

关于java - 使用 XPath 和 XML XPath Api 获取 Soap Body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19308314/

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