2013-04-02 119 views
0

我一直在试图找到一个解决方案,通过网络搜索,并通过许多博客,论坛和网站,我仍然坚持这个问题。XML递归节点解析器

我有这样的XML源:

<?xml version="1.0" encoding="UTF-8" ?> 
<root> 
    <level_one> 
     <level_two> 
     #text 
     </level_two> 
     <level_two> 
     #text 
     </level_two> 
    </level_one> 
</root> 

然后,在Java中我试图解析这个XML文件中递归的方式。这是我的函数:

public void parseXML(Node root, Node parent) 
{ 
    if (root.hasChildNodes()) 
    { 
     NodeList childrens = root.getChildNodes(); 
     for (int i = 0; childrens.getLength(); i++) 
     { 
      parseXML(childrens.item(i), root);   
     }//for 
    }//fi:root_childrens 
    else 
     System.println.out(parent.getNodeName()+"::"+root.getNodeValue()); 
} 

有一次,当我已经加载XML文件,我做的:

xmlDoc.normalize(); 
parseXML(xmlDoc.getFirstChild(), null); 

OK,这个工程......更多或更少。 现在,我得到的回应是:

root:: //OK 
level_one:: //OK 
level_two::#text //OK 
level_one:: //WRONG: should not appear any more 
level_two::#text //OK 
level_one:: //WRONG: should not appear any more 
root:: //WRONG: should not appear any more 

我使用下列库:

import javax.xml.*; 
import org.w3c.dom.*; 

感谢您的帮助。

编辑1:仅供参考。 XML文件比2层更深。

编辑2:如果我改变parent.getNodeName()root.getNodeName(),我得到如下回应:

#text:: 
#text:: 
#text:: 
... 
+0

抱歉,这是我的错误。 –

回答

2

这是因为你的程序显示空文本节点包含如空格: “\ n”

你的XML可以这样来看:

<?xml version="1.0" encoding="UTF-8" ?> 
<root>[A node that contains "\n "] 
    <level_one>[A node that contains "\n "] 
     <level_two> 
     #text 
     </level_two> 
     <level_two> 
     #text 
     </level_two>[A node that contains "\n "] 
    </level_one>[A node that contains "\n "] 
</root> 

这就是节点显示两次的原因。

为了获得所需的输出,你可能会写这样的事情:

public static void parseXML(Node node, Node parent) 
{ 
    if (node.hasChildNodes()) 
    { 
     System.out.println(node.getNodeName()); 
     NodeList childrens = node.getChildNodes(); 
     for (int i = 0; i < childrens.getLength(); i++) 
     { 
      parseXML(childrens.item(i), node);   
     }//for 
    }//fi:root_childrens 
    else { 
     String nodeValue = node.getNodeValue().trim(); 
     if (nodeValue.length() > 0){ 
      System.out.println(parent.getNodeName() + "::" + nodeValue); 
     } 

    } 
} 

,它将打印:

#document 
root 
level_one 
level_two 
level_two::#text 
level_two 
level_two::#text 
+0

是的,存在这个问题。一旦我从“\ n”或“\ t”特殊字符清除了XML文件,代码就可以工作了!谢谢你的帮助。 – Wolfchamane