XPath, XML Namespaces and Java

前端 未结 3 2083
悲&欢浪女
悲&欢浪女 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:08

    SAX (alternative to XPath) version:

    SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
    final String[] number = new String[1];
    DefaultHandler handler = new DefaultHandler()
    {           
        @Override
        public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException
        {
            if (qName.equals("documentnbr"))
                number[0] = attributes.getValue("number");
        }
    };
    saxParser.parse("input.xml", handler);
    System.out.println(number[0]);
    

    I see it's more complicated to use XPath with namespaces as it should be (my opinion). Here is my (simple) code:

    XPath xpath = XPathFactory.newInstance().newXPath();
    
    NamespaceContextMap contextMap = new NamespaceContextMap();
    contextMap.put("custom", "http://www.PureEdge.com/XFDL/Custom");
    contextMap.put("designer", "http://www.PureEdge.com/Designer/6.1");
    contextMap.put("pecs", "http://www.PureEdge.com/PECustomerService");
    contextMap.put("xfdl", "http://www.PureEdge.com/XFDL/6.5");
    contextMap.put("xforms", "http://www.w3.org/2003/xforms");
    contextMap.put("", "http://www.PureEdge.com/XFDL/6.5");
    
    xpath.setNamespaceContext(contextMap);
    String expression = "//:documentnbr/@number";
    InputSource inputSource = new InputSource("input.xml");
    String number;
    number = (String) xpath.evaluate(expression, inputSource, XPathConstants.STRING);
    System.out.println(number);
    

    You can get NamespaceContextMap class (not mine) from here (GPL license). There is also 6376058 bug.

提交回复
热议问题