如何在 Java 中获取 XML 元素的兄弟元素(使用 DOM 解析器)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17641496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i get the siblings of an XML element in Java (using the DOM parser)?
提问by programmer
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:
我在 JAVA 中使用 DOM 解析器的代码如下:
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
提前致谢
回答by McDowell
<parent>
<child1> value 1 </child1>
<child2> value 2 </child2>
<child3> value 3 </child3>
</parent>
What you are getting is the whitespace text nodebetween the child1
and child2
elements.
您得到的是和元素之间的空白文本节点。child1
child2
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());
回答by forty-two
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));
}
回答by mattbdean
When you call this line:
当您拨打此行时:
NodeList elemNodeList = doc.getElementsByTagName("child1");
You are gathering a list of all the elements that have the name "child1". You are expecting elements with the names "child2" and "child3" to be in there also.
您正在收集名称为“child1”的所有元素的列表。您还期望名称为“child2”和“child3”的元素也在其中。
What you can do instead is get the root Element
(which is "parent") through doc.getDocumentElement()
. Then, you can get a NodeList
of that document's child nodes by calling rootElement.getChildNodes()
and then loop through that list.
相反,您可以做的是Element
通过doc.getDocumentElement()
. 然后,您可以NodeList
通过调用rootElement.getChildNodes()
然后遍历该列表来获取该文档的子节点。
回答by Pali
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();
}