parse xml using dom java

前端 未结 3 1971
青春惊慌失措
青春惊慌失措 2021-01-25 20:15

I have the bellow xml:


    
        
            wish
             


        
相关标签:
3条回答
  • 2021-01-25 20:37

    I like to use XMLBeam for such tasks:

    public class Answer {
    
        @XBDocURL("resource://data.xml")
        public interface DataProjection {
    
            public interface Topic {
                @XBRead("./@id")
                int getID();
    
                @XBRead("./@percentage")
                String getPercentage();
            }
    
            @XBRead("/modelingOutput/listOfDocs//document/topic")
            List<Topic> getTopics();
        }
    
        public static void main(final String[] args) throws IOException {
            final DataProjection dataProjection = new XBProjector().io().fromURLAnnotation(DataProjection.class);
            for (Topic topic : dataProjection.getTopics()) {
                System.out.println(topic.getID() + ": " + topic.getPercentage());
            }
        }
    }
    

    There is even a convenient way to convert the percentage to float or double. Tell me if you like to have an example.

    0 讨论(0)
  • 2021-01-25 20:39

    If you do not want to use the if statement you can use XPath to get the element you need directly.

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("source.xml");
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("/*/listOfDocs/documents/document/topic");
    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i).getAttributes().getNamedItem("id"));
        System.out.println(nodes.item(i).getAttributes().getNamedItem("percentage"));
    }
    

    Please check GitHub project here.

    Hope this helps.

    0 讨论(0)
  • 2021-01-25 20:57

    First, when checking the node name you shouldn't compare Strings using ==. Always use the equals method instead.

    You can use XPath to evaluate only the document topic elements under listOfDocs:

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    XPathExpression xPathExpression = xPath.compile("//listOfDocs//document/topic");
    
    NodeList topicnl = (NodeList) xPathExpression.evaluate(dom, XPathConstants.NODESET);
    for(int i = 0; i < topicnl.getLength(); i++) {
       ...
    
    0 讨论(0)
提交回复
热议问题