【发布时间】:2019-08-28 21:13:28
【问题描述】:
我无法使用 XPath 和 DOMParser 读取 XML 元素及其值。客户端在我的应用程序中将此 XML 作为请求发送,我没有任何控制来操作客户端代码。我想使用 DOMParser 读取 AccountID。
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns="https://billpayment.weaut.com/">
<soap:Body>
<GetAccountBalanceByAccount xmlns="https://billpayment.weaut.com/">
<CompanyName>AABC</CompanyName>
<Language>ENG</Language>
<AccountID>54698214</AccountID>
</GetAccountBalanceByAccount>
</soap:Body>
</soap:Envelope>
这就是我试图解析 XML 以获取 AccountID 节点及其内容的方式。
@RequestMapping(value = "/", method = { RequestMethod.POST}, consumes = {"text/xml"}, produces = "text/xml")
public ResponseEntity messageStub(@RequestBody String requestString)
throws ClientProtocolException, IOException {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(requestString)));
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
javax.xml.namespace.NamespaceContext ns = new javax.xml.namespace.NamespaceContext()
{
@Override
public String getNamespaceURI(String prefix)
{
if ( "soap".equals( prefix ) )
{
return "http://www.w3.org/2003/05/soap-envelope";
}
return javax.xml.XMLConstants.NULL_NS_URI;
}
@Override
public String getPrefix(String namespaceURI)
{
return null;
}
@Override
public Iterator<?> getPrefixes(String namespaceURI)
{
return null;
}
};
xpath.setNamespaceContext(ns);
String nodeName="", nodeContent="";
NodeList nodeList = null;
//XML Path
String chkXMLPath="/soap:Envelope/soap:Body/GetAccountBalanceByAccount/AccountID";
XPathExpression expr = xpath.compile(chkXMLPath);
//evaluating each node set against the requested xml
Object result = expr.evaluate(doc, XPathConstants.NODESET);
nodeList = (NodeList) result;
//Here I am getting 0 node
System.out.println("Got " + nodeList.getLength() + " nodes");
for (int i = 0; i < nodeList.getLength(); i++)
{
nodeName = nodeList.item(i).getNodeName();
nodeContent = nodeList.item(i).getTextContent();
System.out.println("\nCurrent Element :" + nodeName);
System.out.println("\nCurrent Value :" + nodeContent);
break;
}
}
}
当我在从这两个地方删除 xmlns 命名空间后测试此方法时,我就能够读取元素及其内容。您能否建议我如何在不修改 XML 的情况下读取 AccountID 及其内容。
【问题讨论】:
-
您是否尝试过实现当前返回
null的方法? -
当前实现返回null。
标签: java eclipse soap xml-parsing