简体   繁体   English

从xml到Java读取子节点的内容

[英]Read the contents of child node from xml to Java

I have been trying to read this xml and fetch the values of id,active and MAIN_ID and store to string values in java as i need to process each values further. 我一直在尝试读取此xml并获取id,active和MAIN_ID的值,并在Java中存储为字符串值,因为我需要进一步处理每个值。 But i could read the Node document ,but iam not sure how to get the values of id ,active and MAIN_ID when we loop though the document. 但是我可以阅读Node文档,但是我不确定在循环浏览文档时如何获取id,active和MAIN_ID的值。 Can someone give me ideas to parse this xml and best way to do it. 有人可以给我一些解析该xml的想法,以及实现该问题的最佳方法。

<add>
<document>
  <field name='id'>Summer id</field>
  <field name='active' update='add'>yes</field>
  <field name='MAIN_ID' update='add'>34242</field>
</doc>
<document>
  <field name='id'>winter id</field>
  <field name='active' update='add'>yes</field>
  <field name='MAIN_ID' update='add'>5354</field>
</document>
<doc>

Right now this is my code .But iam not sure to retrive the child nodes based on fields. 现在这是我的代码。但是我不确定要根据字段来检索子节点。

DocumentBuilder builder = factory.newDocumentBuilder();

        // create a new document from input stream and an empty systemId
        Document doc = builder.parse(url);

        // get the first element
        Element element = doc.getDocumentElement();
        System.out.println("element" + element);

        // get all child nodes
        NodeList nodes = element.getChildNodes();

        // print the text content of each child
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (node instanceof Element) {
                //need to know how to parse the child elements for above code
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

First consider not using attributes in XML to specify node meaning, so instead have something like this 首先考虑不要在XML中使用属性来指定节点的含义,所以要有类似这样的内容

...
<document>
  <id>winter id</id>
  <active update='add'>yes</active>
  <MAIN_ID update='add'>5354</MAIN_ID>
</document>
...

If your document is large, consider learning about and using a SAX parser. 如果您的文档很大,请考虑学习和使用SAX解析器。 However if you want to use DOM, look at the org.w3c.dom.Element interface. 但是,如果要使用DOM,请查看org.w3c.dom.Element接口。 There are lots of step by step posts on SO on how to parse HTML using DOM, like this one . 在SO上有很多关于如何使用DOM解析HTML的分步指南,就像这篇文章 But you want getElementsByTagName for elements named "document", then pull the individual fields from that Element using the same methods to get id, active, etc. 但是,您希望将getElementsByTagName用于名为“ document”的元素,然后使用相同的方法从该Element中提取各个字段以获取id,active等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM