Sample code for 30+ languages & platforms
Xbase++

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 Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oXml
LOCAL oChild
LOCAL nNumWithTag
LOCAL i

nSuccess := 0

oXml := CreateObject("Chilkat.Xml")

//  The sample input XML is available at http://www.chilkatsoft.com/data/fruit.xml
nSuccess := oXml:LoadXmlFile("fruit.xml")
IF (nSuccess != 1)
    ? oXml:LastErrorText
    oXml:destroy()
    RETURN
ENDIF

//   Get the number of direct children having the tag "fruit";
nNumWithTag := oXml:NumChildrenHavingTag("fruit")

IF (nNumWithTag > 0)

    FOR i := 0 TO nNumWithTag - 1
        oChild := oXml:GetNthChildWithTag("fruit", i)
        ? Str(i) + ": " + oChild:Tag + " : " + oChild:Content
        oChild:destroy()
    NEXT
    ? "-----"

    //  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 i := 0 TO nNumWithTag - 1
        //  Navigate to the Nth child.  
        nSuccess := oXml:GetNthChildWithTag2("fruit", i)
        ? Str(i) + ": " + oXml:Tag + " : " + oXml:Content
        //  Navigate back up to the parent:
        nSuccess := oXml:GetParent2()
    NEXT
    ? "-----"
ENDIF

oXml:destroy()