使用xpath在Java中使用名称空间解析XML

我试图在java中解析SOAP请求,但代码没有返回任何节点这里是代码可以任何人发现错误

String xml="dfasf@google.comPfasdfRem91"; System.out.println(xml); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(xml))); XPath xpath = XPathFactory.newInstance().newXPath(); // XPath Query for showing all nodes value try { XPathExpression expr = xpath.compile("/soapenv:Envelope/soapenv:Header/authInfo/password"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; System.out.println("Got " + nodes.getLength() + " nodes"); // System.out.println(nodes.item(0).getNodeValue()); } catch(Exception E) { System.out.println(E); } 

您需要在XPath上设置NamespaceContext

演示

 package forum11644994; import java.io.StringReader; import java.util.Iterator; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.*; import javax.xml.xpath.*; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class Demo { public static void main(String[] args) throws Exception { String xml = "dfasf@google.comPfasdfRem91"; System.out.println(xml); DocumentBuilderFactory domFactory = DocumentBuilderFactory .newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(xml))); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new NamespaceContext() { @Override public Iterator getPrefixes(String arg0) { return null; } @Override public String getPrefix(String arg0) { return null; } @Override public String getNamespaceURI(String arg0) { if("soapenv".equals(arg0)) { return "http://schemas.xmlsoap.org/soap/envelope/"; } return null; } }); // XPath Query for showing all nodes value try { XPathExpression expr = xpath .compile("/soapenv:Envelope/soapenv:Header/authInfo/password"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; System.out.println("Got " + nodes.getLength() + " nodes"); // System.out.println(nodes.item(0).getNodeValue()); } catch (Exception E) { System.out.println(E); } } } 

产量

 dfasf@google.comPfasdfRem91 Got 1 nodes 

在最新的回复中添加更多内容。要获取特定的节点值,可以使用以下 – [ System.out.println(nodes.item(0).getTextContent()); ]