简体   繁体   English

如何在Java中获取XML元素的兄弟(使用DOM解析器)?

[英]How can i get the siblings of an XML element in Java (using the DOM parser)?

I would like to get the siblings of an XML element in Java. 我想在Java中获取XML元素的兄弟姐妹。

The xml file is as follows: xml文件如下:

  <parent>
    <child1> value 1 </child1>
    <child2> value 2 </child2>
    <child3> value 3 </child3>
  </parent>

My code in JAVA with DOM parser is as follows: 我在带有DOM解析器的JAVA中的代码如下:

 package dom_stack;

 import java.io.File;
 import java.io.IOException;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 import org.w3c.dom.Document;
 import org.w3c.dom.NodeList;
 import org.xml.sax.SAXException;


 public class DOM_stack {


     public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {


      File file = new File("root.xml");
      if (file.exists()){
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

            Document doc;
             doc = dbf.newDocumentBuilder().parse("root.xml");


            NodeList elemNodeList = doc.getElementsByTagName("child1");                 

            for(int j=0; j<elemNodeList.getLength(); j++) {

                System.out.println("The node's value that you are looking now is : " +  elemNodeList.item(j).getTextContent());
                System.out.println(" Get the Name of the Next Sibling " + elemNodeList.item(j).getNextSibling().getNodeName());
                System.out.println(" Get the Value of the Next Sibling " + elemNodeList.item(j).getNextSibling().getNodeValue());

            }


        }//if file exists
     }
    }

Unfortunately the result is: 不幸的是结果是:

    run:
    The node's value that you are looking now is :  value 1 
     Get the Name of the Next Sibling #text
     Get the Value of the Next Sibling 

and it should be: 它应该是:

    run:
    The node's value that you are looking now is :  value 1 
     Get the Name of the Next Sibling child2
     Get the Value of the Next Sibling value2

So, how can i get the desirable output? 那么,我怎样才能获得理想的输出?

thanks, in advance 提前致谢

<parent>
  <child1> value 1 </child1>
  <child2> value 2 </child2>
  <child3> value 3 </child3>
</parent>

What you are getting is the whitespace text node between the child1 and child2 elements. 你得到的是child1child2元素之间的空白文本节点

You need to keep walking the siblings to skip over whitespace, comments, etc, to get the next element node : 你需要继续走兄弟姐妹,跳过空白,评论等,以获得下一个元素节点

Node child1 = elemNodeList.item(j);
Node sibling = child1.getNextSibling();
while (!(sibling instanceof Element) && sibling != null) {
  sibling = sibling.getNextSibling();
}
System.out
      .println(" Get the Name of the Next Sibling " + sibling.getNodeName());
System.out
      .println(" Get the Value of the Next Sibling " + sibling.geTextContent());

Or, you can do it easily with XPath: 或者,您可以使用XPath轻松完成:

    XPath xp = XPathFactory.newInstance().newXPath();

    // Select the first child of the root element
    Element c1 = (Element) xp.evaluate("/parent/*[1]", doc,
            XPathConstants.NODE);

    // Select the siblings of the first child
    NodeList siblings = (NodeList) xp.evaluate("following-sibling::*", c1,
            XPathConstants.NODESET);
    for (int i = 0; i < siblings.getLength(); ++i) {
        System.out.println(siblings.item(i));
    }

When you call this line: 当你拨打这一行时:

NodeList elemNodeList = doc.getElementsByTagName("child1");

You are gathering a list of all the elements that have the name "child1". 您正在收集名称为“child1”的所有元素的列表。 You are expecting elements with the names "child2" and "child3" to be in there also. 您期望名称为“child2”和“child3”的元素也在其中。

What you can do instead is get the root Element (which is "parent") through doc.getDocumentElement() . 你可以做的是通过doc.getDocumentElement()获取根Element (它是“父” doc.getDocumentElement() Then, you can get a NodeList of that document's child nodes by calling rootElement.getChildNodes() and then loop through that list. 然后,您可以通过调用rootElement.getChildNodes()获取该文档的子节点的NodeList ,然后循环遍历该列表。

Since @McDowell 's solution haven't worked for me I changed it a bit and got it working so the Node sibling will be the "next" xml tag (e,g, if the Node current is <child1> , the Node sibling will be <child2> ): 由于@McDowell的解决方案对我不起作用,我改变了一点并使其工作,因此Node sibling将成为“下一个”xml标签(例如,如果Node current<child1> ,那么Node sibling将是<child2> ):

Node sibling = current.getNextSibling();
while (null != sibling && sibling.getNodeType() != Node.ELEMENT_NODE) {
    sibling = sibling.getNextSibling();
}

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

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