我正在遍历SoapMessage的这个肥皂故障XML响应。我可以解析节点并找到所需的Node,但是如何将Node值返回给调用方法。当我再次调用相同的方法来获取值时。这是我的代码。
Response XML:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
<soapenv:Body>
<soapenv:Fault>
<soapenv:Code>
<soapenv:Value>soapenv:Receiver</soapenv:Value>
</soapenv:Code>
<soapenv:Reason>
<soapenv:Text xml:lang="en">Failed</soapenv:Text>
</soapenv:Reason>
<Detail xmlns="http://www.w3.org/2003/05/soap-envelope">
<axis2:documentFault xmlns:axis2="http://XXXXXXXXXXXXXXX" xmlns:ns2="http://XXXXXXXXXXXXXXX.xsd" xmlns:ns3="http://XXXXXXXXXXXXXXX.xsd">
<axis2:SystemInfo>
<axis2:ServiceContext>
<axis2:consumerPartnerId>XXX</axis2:consumerPartnerId>
</axis2:ServiceContext>
<axis2:ReturnInfo>
<axis2:returnSeverity>Error</axis2:returnSeverity>
<axis2:commonReturnMessage>Exception</axis2:commonReturnMessage>
<axis2:ReturnInfo>
<axis2:ReturnCode>008</axis2:ReturnCode>
<axis2:ReturnMessage>This is the response error description</axis2:ReturnMessage>
</axis2:ReturnInfo>
</axis2:ReturnInfo>
</axis2:SystemInfo>
</axis2:documentFault>
</Detail>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>
Element dom = responseBody;
// Calling method
String soapResult = getChildren(dom);
// rest of the code
private String getChildren(Node n){
NodeList innerResultList = n.getChildNodes();
String value="";
for (int l = 0; l < innerResultList.getLength(); l++) {
Node currentNode = innerResultList.item(l);
System.out.println(currentNode.getNodeName());
String name = currentNode.getNodeName();
if(name.contains("Status")) {
value = currentNode.getTextContent();
System.out.println(value);
//result.put("result", value);
}else if(name.contains("ReturnMessage")) {
value = currentNode.getTextContent();
System.out.println(value);
//result.put("result", value);
}
getChildren(currentNode);
}
return value;
}
最佳答案
我强烈建议使用XPath。在这种情况下,您可以通过以下两行获得<axis2:ReturnMessage>
值:
XPath xPath = XPathFactory.newInstance().newXPath();
String returnMessage = xPath.compile("//Detail//ReturnMessage").evaluate(dom));
在
//Detail//ReturnMessage
的特殊情况下,我假设第一个ReturnMessage
具有祖先元素Detail
来获取。您可以根据需要修改此提取逻辑。编辑:这是根据OP要求的完整资源:
import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
public class Main {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document dom = builder.parse(new FileInputStream("c://tmp//tmp.xml"));
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.println(xPath.compile("//Detail//ReturnMessage").evaluate(dom));
}
}