问题描述
我有这个XML文件:
<root>
<node1>
<name>A</name>
<node2>
<name>B</name>
<node3>
<name>C</name>
<number>001</number>
</node3>
</node2>
</node1>
</root>
我正在解析文件,以获取每个节点的名称以及相应的编号(如果存在)。
I am parsing the file, to get the name for each node, and the corresponding number if existing.
我使用:
String number = eElement.getElementsByTagName("number").item(0).getTextContent();
这应该给我类似的东西:
This should give me something like:
Name | Number
A |
B |
C | 001
但是我得到:
Name | Number
A | 001
B | 001
C | 001
所以,我认为 getElementsByTagName( Number)
在节点的所有子节点中寻找数字节点。我不要有人知道解决方法吗?
So, I think the getElementsByTagName("Number")
is looking for number node in all the children of a node. I don't want that. Does anybody know a workaround?
我想到了使用XPath代替上述方法,但是我真的很想知道是否存在现有方法。谢谢
I thought of using XPath instead of the above method, but I really want to know if there's an existing way. Thanks
推荐答案
您可以使用 javax.xml.xpath
API JDK / JRE对通过 getElementsByTagName
返回的XML进行更多控制。
You can use the javax.xml.xpath
APIs in the JDK/JRE to have much more control over the XML returned over getElementsByTagName
.
import java.io.File;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("filename.xml"));
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
Element element = (Element) xpath.evaluate("//node3/name", document, XPathConstants.NODE);
}
}
这篇关于getElementsByTagName向下搜索所有级别的XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!