从xml中排除特定标签?

时间:2012-11-29 10:39:16

标签: java xml jsoup

我正在使用jsoup从带有xmlDoc.select("ns|properties")

的xml文件中提取一些属性

问题:它找到了所有“属性”标签的出现。我只想要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>

1 个答案:

答案 0 :(得分: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

相关问题