简体   繁体   English

如何获取NodeList中每个节点的第一个子节点的值?

[英]How to get the value of each node's first child in NodeList?

Id like to get the element name and value of the first child of each element. 想要获取每个元素的第一个子元素的元素名称和值。 But I'm getting null values. 但是我得到空值。 Im pretty new to XML and I am stumped, just trying to get something working with pretty font. 我对XML来说还很陌生,我很困惑,只是想让某些字体能正常工作。 Theres about 15 children to the root, and theyre all called "DEvent", I would like my output to be: 大约有15个孩子,它们都被称为“ DEvent”,我希望我的输出是:

Event: Wednesday Trail Walks 事件:周三步道

Event: BOW - Dog Mushing! 事件:弓-狗猛扑!

etc. 等等

    <DNREvents>
<DEvent>
<event eid="1">Wednesday Trail Walks</event>
<date>2/03/2016</date>
<time>1-2:30 PM</time>
<description>...</description>
<location>Brown's Creek State Trail</location>
<cost>Free</cost>
<infoPhone>651-231-6968</infoPhone>
<infoEmail>LindaRadimecky@state.mn.us</infoEmail>
</DEvent>
<DEvent>
<event eid="2">BOW - Dog Mushing!</event>
<date>2/04/2016 thru 2/07/2016</date>
<time>Unknown</time>
<description>
This off the grid adventure is for those who want to actively participate in every aspect of learning to run your own small team of sled dogs through miles and miles of beautiful trails in the remote wilderness of northern Minnesota. Limited to 4 participants
</description>
<location>Grand Marais/Hovland</location>
<cost>$895</cost>
<infoPhone>218-370-0283</infoPhone>
<infoEmail>linda@points_unknown.com</infoEmail>
</DEvent>
<DEvent>...</DEvent>
<DEvent>...</DEvent>
<DEvent>...</DEvent>
<DEvent>...</DEvent>
<DEvent>...</DEvent>
<DEvent>...</DEvent>
<DEvent>...</DEvent>
<DEvent>...</DEvent>
<DEvent>...</DEvent>
<DEvent>...</DEvent>
<DEvent>...</DEvent>
<DEvent>...</DEvent>
<DEvent>...</DEvent>
</DNREvents>

My java to show the results- 我的Java显示结果-

Element DNR = root;
        NodeList EventList=DNR.getElementsByTagName("DEvent");
        for (int i=0; i< EventList.getLength();i++)
        {
            Node thisNode = EventList.item(i);
            Node child = thisNode.getFirstChild();
            String x = child.getNodeValue();
            System.out.println(thisNode+ x);
        }

Here is a working example. 这是一个工作示例。 The firstChild in your code was a #Text node and you needed to get the nextSibling() of that node (So your event node is not the first node after all): 您代码中的firstChild是一个#Text节点,您需要获取该节点的nextSibling()(因此,您的事件节点毕竟不是第一个节点):

    import org.w3c.dom.*;
    import java.io.*;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;

    File xmlFile = new File("/data/test/test.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(xmlFile);

    NodeList eventList = doc.getElementsByTagName("DEvent");
    for (int i=0; i< eventList.getLength(); i++) {
        Node thisNode = eventList.item(i);

        if(thisNode.hasChildNodes()){
            NodeList event = thisNode.getChildNodes().getFirstChild().getNextSibling();
            String eid = event.getAttributes().getNamedItem("eid");
            String value = event.getFirstChild().getNodeValue();
            System.out.println("EID: " + eid + " Value: " + value + "\n");
        }
    }

Be aware that this line will be fragile if you don't do additional null checking to verify the xml is well formed with the proper child nodes. 请注意,如果您不执行其他空检查来验证xml是否具有正确的子节点格式,则此行将非常脆弱。 And, this doesn't enforce the order of the child nodes in the xml is in the order you expect: 而且,这不会强制xml中子节点的顺序与您期望的顺序相同:

NodeList child = thisNode.getChildNodes().getFirstChild().getNextSibling();

With that said, I think a better implementation would be to use XPath, which allows you to select the nodes you want without traversing manually down the tree and is more compact and 'fail safe': 话虽如此,我认为一种更好的实现方式是使用XPath,它使您可以选择所需的节点,而无需手动遍历树,并且更加紧凑和“故障保护”:

    XPath xpath = XPathFactory.newInstance().newXPath();
    String expression = "/DNREvents/DEvent/event";
    InputSource inputSource = new InputSource(new BufferedReader(new FileReader("/data/test/test.xml")));
    NodeList eventList = (NodeList) xpath.evaluate(expression, inputSource, XPathConstants.NODESET);

    for (int i=0; i< eventList.getLength(); i++) {
        Node eventNode = eventList.item(i);

        String eid = xpath.evaluate("@eid", eventNode);
        String value = xpath.evaluate("./text()", eventNode);
        System.out.println("EID: " + eid + ", Value: " + value + "\n");
    }

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

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