簡體   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