繁体   English   中英

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

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

我想在Java中获取XML元素的兄弟姐妹。

xml文件如下:

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

我在带有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
     }
    }

不幸的是结果是:

    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 

它应该是:

    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

那么,我怎样才能获得理想的输出?

提前致谢

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

你得到的是child1child2元素之间的空白文本节点

你需要继续走兄弟姐妹,跳过空白,评论等,以获得下一个元素节点

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());

或者,您可以使用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));
    }

当你拨打这一行时:

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

您正在收集名称为“child1”的所有元素的列表。 您期望名称为“child2”和“child3”的元素也在其中。

你可以做的是通过doc.getDocumentElement()获取根Element (它是“父” doc.getDocumentElement() 然后,您可以通过调用rootElement.getChildNodes()获取该文档的子节点的NodeList ,然后循环遍历该列表。

由于@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