如何在 Java 中获取 XML 元素的兄弟元素(使用 DOM 解析器)? [英] How can i get the siblings of an XML element in Java (using the DOM parser)?
本文介绍了如何在 Java 中获取 XML 元素的兄弟元素(使用 DOM 解析器)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 Java 中获取 XML 元素的兄弟元素.
I would like to get the siblings of an XML element in Java.
xml文件如下:
<parent>
<child1> value 1 </child1>
<child2> value 2 </child2>
<child3> value 3 </child3>
</parent>
我在 JAVA 中使用 DOM 解析器的代码如下:
My code in JAVA with DOM parser is as follows:
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
那么,我怎样才能获得理想的输出?
So, how can i get the desirable output?
谢谢,提前
推荐答案
<parent>
<child1> value 1 </child1>
<child2> value 2 </child2>
<child3> value 3 </child3>
</parent>
你得到的是空白 textchild1
和 child2
元素之间的节点.
What you are getting is the whitespace text node between the child1
and child2
elements.
您需要继续走兄弟姐妹以跳过空格、注释等,以获得下一个元素节点:
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());
这篇关于如何在 Java 中获取 XML 元素的兄弟元素(使用 DOM 解析器)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文