how to get the attribute value of an xml node using java

前端 未结 6 819
抹茶落季
抹茶落季 2020-12-03 13:59

I\'ve an xml which looks like this:

{ .....         


        
6条回答
  •  离开以前
    2020-12-03 14:45

    try something like this :

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document dDoc = builder.parse("d://utf8test.xml");
    
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList) xPath.evaluate("//xml/ep/source/@type", dDoc, XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            System.out.println(node.getTextContent());
        }
    

    please note the changes :

    • we ask for a nodeset (XPathConstants.NODESET) and not only for a single node.
    • the xpath is now //xml/ep/source/@type and not //xml/source/@type/text()

    PS: can you add the tag java to your question ? thanks.

提交回复
热议问题