0

我正在使用 jsoup 从 xml 文件中提取一些属性xmlDoc.select("ns|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>
4

1 回答 1

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

于 2012-11-29T18:10:14.760 回答