1
<level levelid="1">
<chapter>1<chapter>
<mintime>100</mintime>
<maxtime>18000</maxtime>
<totalhexes>7</total>
<target>
    <targettype>2</targettype>
    <targetrestraint>0</targetrestraint>
    <targetcondition>2</targetcondition>
    <targetvalue>1980</targetvalue>
</target>
<target>
    <targettype>1</targettype>
    <targetrestraint>0</targetrestraint>
    <targetcondition>0</targetcondition>
    <targetvalue>3000</targetvalue>
</target>

....

When trying to read the different targets. Knowing they are 3 targets, I try to cycle through them using the following code:

    for (int i = 1; i <= 3; i++) {
        XmlReader.Element star = elements
                .getChildByName("target");
        type = star.getInt("ns1:targettype");
        restraint = star.getInt("targetrestraint");
        condition = star.getInt("targetcondition");
        value = star.getInt("targetvalue");
        target.setTargetstar(i, type, restraint, condition, value);     
    }   

But I always get the values for the first target, doesn't matter if I set star as either one of:

XmlReader.Element star = elements.getChildByName("target");

or

XmlReader.Element star = elements.getChildByNameRecursive("target");

What method do I use to read all of the three "target" children?

2 Answers 2

1

Use getChildrenByName():

for (XmlReader.Element target : elements.getChildrenByName("target")) {
    // this should be iterated three times, once for each target
}   
1

You always take the first child by using getChildByName.
Instead you should use getChildrenByName, which gives you all children with this name. You can easily use the foreach loop to cycle through them:

for(XmlReader.Element target : elements.getChildrenByName("target")) {
    type = target.getInt("targettype");
    restraint = element.getInt("targetrestraint");
    // Rest of code here
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.