带命名空间的DOM4J xpath-select冒号节点

时间:2016-08-31 08:59:25

标签: java namespaces dom4j

鉴于xml内容如下;

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><CreateResponse xmlns="http://gtestserver/"><CustomerId>8124138</CustomerId><InternalResponseCode>Success</InternalResponseCode><ResponseCode>0</ResponseCode><ResponseDate>2016-08-31T07:57:22.7760577Z</ResponseDate><ResponseDescription>Success</ResponseDescription><UserId>7424876375</UserId></CreateResponse></s:Body></s:Envelope>

我需要接收节点: CustomerId ,但我无法正确理解,我在这里使用的代码:

 Document document = new SAXReader().read(new ByteArrayInputStream(xmlfile.getBytes("UTF-8")));
 Node foundnode = null;
 Element rootElement = document.getRootElement();
 String namespace = rootElement.getNamespaceURI();
 if (namespace != null) {
     DefaultXPath defaultXPath = new DefaultXPath(xpath);
     Map<String, String> namespaces = new TreeMap<String, String>();
     namespaces.put("ns", namespace);
     defaultXPath.setNamespaceURIs(namespaces);
 }
 foundnode = document.selectSingleNode("/ns:s:Envelope/ns:s:Body/ns:CreateResponse/ns:CustomerId");

然后它抛出异常:

org.dom4j.InvalidXPathException: Invalid XPath expression: /ns:s:Envelope/ns:s:Body/ns:CreateResponse/ns:CustomerId Unexpected ':'
    at org.dom4j.xpath.DefaultXPath.parse(DefaultXPath.java:360)
    at org.dom4j.xpath.DefaultXPath.<init>(DefaultXPath.java:59)
    at com.github.becauseQA.xml.DOM4JUtils.getNodes(DOM4JUtils.java:152)
    at 

我知道它是由这里使用的xpath引起的,但是我不知道我应该在这里拾取哪个xpath,你可以看到节点有:,所以当使用带有ns的命名空间时:对于每个节点,它都无法解析它。任何人都知道如何在节点名称中使用命名空间和特殊字符拾取节点?谢谢。

1 个答案:

答案 0 :(得分:2)

您可以尝试以下操作:

String xml = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><CreateResponse xmlns=\"http://gtestserver/\"><CustomerId>8124138</CustomerId><InternalResponseCode>Success</InternalResponseCode><ResponseCode>0</ResponseCode><ResponseDate>2016-08-31T07:57:22.7760577Z</ResponseDate><ResponseDescription>Success</ResponseDescription><UserId>7424876375</UserId></CreateResponse></s:Body></s:Envelope>";

Document document = new SAXReader().read(new ByteArrayInputStream(xml.getBytes("UTF-8")));
Node foundnode = null;
Element rootElement = document.getRootElement();
String namespace = rootElement.getNamespaceURI();

foundnode = document.selectSingleNode("//*[local-name()='CustomerId']");

System.out.println(foundnode.getText());

返回:8124138