Sample code for 30+ languages & platforms
Java

Iterate over Direct Children with a Specific Tag

See more XML Examples

Demonstrates how to iterate over direct children having a specific tag.

The input XML, available at http://www.chilkatsoft.com/data/fruit.xml, is this:

<root>
    <fruit color="red">apple</fruit>
    <fruit color="green">pear</fruit>
    <veg color="orange">carrot</veg>
    <meat animal="cow">beef</meat>
    <xyz>
        <fruit color="blue">blueberry</fruit>
        <veg color="green">broccoli</veg>
    </xyz>
    <fruit color="purple">grape</fruit>
    <cheese color="yellow">cheddar</cheese>
</root>

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Xml;

public class ChilkatExample {

    public static void main(String[] args) {
        Xml xml = new Xml();
        Xml child = null;

        // The sample input XML is available at http://www.chilkatsoft.com/data/fruit.xml
        try {
            xml.loadXmlFile("fruit.xml");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        //  Get the number of direct children having the tag "fruit";
        int numWithTag = xml.numChildrenHavingTag("fruit");

        if (numWithTag > 0) {
            for (int i = 0; i < numWithTag; i++) {
                child = xml.getNthChildWithTag("fruit", i);
                System.out.println(i + ": " + child.getTag() + " : " + child.getContent());
                child.close();
            }

            System.out.println("-----");

            // Do the same as the above loop, but instead of creating
            // a new object instance for each child, call GetNthChildWithTag2 to
            // update the object's reference instead.
            for (int i = 0; i < numWithTag; i++) {
                // Navigate to the Nth child.
                xml.getNthChildWithTag2("fruit", i);
                System.out.println(i + ": " + xml.getTag() + " : " + xml.getContent());
                // Navigate back up to the parent:
                xml.getParent2();
            }

            System.out.println("-----");
        }
    }
}