tosi
tosi

Reputation: 1925

ant Task for or foreach loop in xml files

I need some help on looping through an xml file which I manged to get the nodes using xmlproperty but I am struggling on how to loop through them where there are more than one params.

So here is the format:

<Problems>
      <Problem>
        <Rule>1</Rule>
        <ProblemDescription>1</ProblemDescription>
        <SourceFile>1</SourceFile>
        <Line>1</Line>
        <Column>1</Column>
        <Severity>Warning</Severity>
     </Problem>
     <Problem>
       <Rule>2</Rule>
       <ProblemDescription>2</ProblemDescription>
       <SourceFile>2</SourceFile>
       <Line>2</Line>
       <Column>2</Column>
      <Severity>Warning</Severity>
     </Problem>
</problems>

I want to loop through this so I can get the following output:

1 1 1 1 1 1 2 2 2 2 2

Solution:

  <target>
    <taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask"/>
      <xmltask source="problem.xml">

        <call path="/Problems/Problem">
            <param name="rule" path="Rule/text()" />
            <param name="probdesc" path="ProblemDescription/text()" />
            <actions>
                <echo>Rule: @{rule}</echo>
                <echo>Problem Description: @{probdesc}</echo>
            </actions>
            </call>
    </target>

Upvotes: 0

Views: 2529

Answers (2)

Tinman
Tinman

Reputation: 786

Haven't used ANT in years, not since I switched to maven.

When I was using ant I would create a custom ant task for this sort of functionality. Then you have the full power of java and far more readable code, at the cost of having to compile the task if you need to make changes.

It really depends on what you are going to do with the output. The other answer with xpath is more appropriate if your doing something really simple.

See: http://ant.apache.org/manual/develop.html http://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html

Upvotes: 0

Jeanne Boyarsky
Jeanne Boyarsky

Reputation: 12266

You can use an XPATH expression to return everything that matches a given pattern. In your case, the value of certain tags.

Here is an XPATH Ant task.

Upvotes: 1

Related Questions