我正在通过 StackOverflow 寻找,但我找不到最佳答案。我需要在 JAVA 中读取 XML 文件。我的 XML 文件如下所示:`
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<server>
<server01>
<department>A1</department>
<department>A2</department>
</server01>
<server02>
<department>A1</department>
<department>A2</department>
</server02>
</server>
是否有可能在<server01>
和之间读取 Java 元素<server02>
,不包括文件的其余部分?或者我需要使用不同的标签?我找到了如何读取父节点的方法:
NodeList serversNames = xmlD.getDocumentElement().getChildNodes();
for (int i = 0; i < serversNames.getLength(); i++) {
Node node = serversNames.item(i);
if (node instanceof Element) {
Element childElement = (Element) node;
System.out.println("tag name: " + childElement.getTagName());
}
}
我能够读取所有部门标签并将它们保存到数组中:
NodeList serverName = xmlD.getElementsByTagName("department");
serversList = new String[serverName.getLength()];
System.out.println("zasieg: " + serverName.getLength());
for (int temp = 0; temp < serverName.getLength(); temp++) {
Element shareName = null;
shareName = (Element) serverName.item(temp);
serversList[temp] = shareName.getTextContent();
System.out.println(temp + " - " + serversList[temp]);
}
那么,是否有可能只读取父节点的元素?仅 SERVER01 的元素?