我正在使用此方法从xml文件中读取所有节点。但似乎我的递归不起作用,因为所有节点都是#text节点。如何跳过它并使其返回我的实际节点?
private void iterateNodes(Node node) {
System.out.println("Node: " + node.getNodeName());
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentode = nodeList.item(0);
System.out.println(currentode.getNodeName());
if (currentode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) currentode;
iterateNodes(element);
}
}
}
public void run() throws ParserConfigurationException, SAXException, IOException {
String path = "others.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(path);
document.getDocumentElement().normalize();
iterateNodes(document.getDocumentElement());
}
答案 0 :(得分:4)
您在Node currentode = nodeList.item(0)
中编码&lt; ----使用迭代器变量i更改它。
private void iterateNodes(Node node) {
System.out.println("Node: " + node.getNodeName());
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentode = nodeList.item(i);
System.out.println(currentode.getNodeName());
if (currentode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) currentode;
iterateNodes(element);
}
}
}