我有一个关于在XML for Java中解析节点的问题。
以下代码:
public static String returnNodes(Node node, String node2) {
// do something with the current node instead of System.out
System.out.println("Test1: " + node.getNodeName());
String result = "";
result = node.getNodeName();
// Just for testing purposes
if (result.equals(node2)) {
return "YES!";
}
if (!result.equals(node2)) {
System.out.println("Test2");
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
//calls this method for all the children which is Element
returnNodes(currentNode, node2);
}
}
}
return result;
}
我想证明node2
是否等于当前node
,如果匹配,则返回名为result的变量中的值。
目前我只是得到了我的文档的根元素,如果我调用这个方法,我不知道为什么。然而,&#34;是的!&#34;永远不会在我的控制台上打印,尽管System.out.println("Test1: " + node.getNodeName());
打印&#34;演员&#34;如果我以这种方式调用方法:
returnNodes(document.getFirstChild(), "actor");
- 所以结果总是&#34; log&#34;。
xml结构如下所示:
<?xml version="1.0" encoding="UTF-8" ?>
<log>
<published>2014-03-28T15:28:36.646Z</published>
<actor>
<objectType>person</objectType>
<id>e1b8948f-321e-78ca-d883-80500aae71b5</id>
<displayName>anonymized</displayName>
</actor>
<verb>update</verb>
<object>
<objectType>concept</objectType>
<id>a1ad6ace-c722-ffa9-f58e-b4169acdb4e3</id>
<content>time</content>
</object>
<target>
<objectType>conceptMap</objectType>
<id>4b8f69e3-2914-3a1a-454e-f4c157734bd1</id>
<displayName>my first concept map</displayName>
</target>
<generator>
<objectType>application</objectType>
<url>http://www.golabz.eu/content/go-lab-concept-mapper</url>
<id>c9933ad6-dd4a-6f71-ce84-fb1676ea3aac</id>
<displayName>ut.tools.conceptmapper</displayName>
</generator>
<provider>
<objectType>ils</objectType>
<url>http://graasp.epfl.ch/metawidget/1/b387b6f</url>
<id>10548c30-72bd-0bb3-33d1-9c748266de45</id>
<displayName>unnamed ils</displayName>
</provider>
</log>
如果我想以递归方式打印出我需要的节点,我该怎么办?
答案 0 :(得分:0)
我想回答我自己的问题。我寻找的解决方案并不是真正的递归,而是迭代,但导致我寻找的结果相同。
public static String getNode(Document document, String search) {
NodeList nodeList = document.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(search)) {
// do something with the current element
return node.getNodeName();
}
}
return null;
}