XPath, XML Namespaces and Java

前端 未结 3 2069
悲&欢浪女
悲&欢浪女 2020-12-19 09:47

I\'ve spent the past day attempting to extract a one XML node out of the following document and am unable to grasp the nuances of XML Namespaces to make it work.

The

3条回答
  •  囚心锁ツ
    2020-12-19 10:06

    Have a look at the XPathAPI library. It is a simpler way to use XPath without messing with the low-level Java API, especially when dealing with namespaces.

    The code to get the number attribute would be:

    String num = XPathAPI.selectSingleNodeAsString(doc, '//documentnbr/@number');
    

    Namespaces are automatically extracted from the root node (doc in this case). In case you need to explicitly define additional namespaces you can use this:

    Map nsMap = new HashMap();
    nsMap.put("xforms", "http://www.w3.org/2003/xforms");
    
    String num =
        XPathAPI.selectSingleNodeAsString(doc, '//documentnbr/@number', nsMap);
    

    (Disclaimer: I'm the author of the library.)

提交回复
热议问题