2012-11-29 82 views
0

我正在使用jsoup从xml文件中提取一些属性xmlDoc.select("ns|properties")从xml中排除特定标签?

问题:它找到所有“properties”标记的出现。我只想要ns:tests标签之外的属性。 我该如何排除它们?

<ns:interface> 
</ns:interface> 

<ns:tests> 
    <ns:properties> 
    <ns:name>name</ns:name> 
    <ns:id>2</ns:id> 
    </ns:properties> 
</ns:test> 

<ns:properties> 
    <ns:name>name</ns:name> 
    <ns:id>1</ns:id> 
</ns:properties> 
+0

你在你的xml中有一个错字:开始标记是'ns:tests',但是关闭是'ns:test'。 – ollo

回答

0

您可以尝试以下两种方法:

/* 
* Solution 1: Check if a 'ns:properties' is inside a 'ns:tests' 
*/ 
for(Element element : xmlDoc.select("ns|properties")) 
{ 
    if(element.parent() != null && !element.parent().tagName().equals("ns:tests")) 
    { 
     /* Only elements outside 'ns:tests' here */ 
     System.out.println(element); 
    } 
} 


/* 
* Solution 2: removing all 'ns:tests' elements (including all inner nodes. 
* 
* NOTE: This will DELETE them from 'xmlDoc'. 
*/ 
xmlDoc.select("ns|tests").remove(); 
Elements properties = xmlDoc.select("ns|properties"); 

System.out.println(properties); 

如果选择解决方案2,使舒尔你备份xmlDoc(如克隆)。