简体   繁体   中英

Exclude specific tags from xml?

I'm using jsoup to extract some properties from an xml file with xmlDoc.select("ns|properties")

Problem: it finds all occurences of "properties" tag. I only want the properties outside the ns:tests tags. How can I exclude them?

<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>

You can try these two ways:

/*
 * 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);

If you choose Solution 2 , make shure you backup (eg. clone) xmlDoc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM