user1587504
user1587504

Reputation: 764

Retrieving Xml element's attribute value based on top level element's attribute value

My sample Xml looks like:

<root>
    <Month name="Jan">
        <foo someAttr="bar"/>
    </Month>

    <Month name="July">
        <foo someAttr="zzz"/>
    </Month>

</root>

And when I say:

<xmlproperty file="${root.dir}/my.xml" keeproot="false"/>

<echo message="Month.foo : ${Month.foo(someAttr)}"/> 

prints me bar,zzz. I want to retrieve someAttr value of foo xml element based on month name. for eg get me Month.foo(someAttr) where Month.name="Jan"

Is there a way suppored in Ant, or should I have define my rules with xslt as per another related query : xmlproperty and retrieving property value of xml element if specific attribute is present/set

Upvotes: 2

Views: 414

Answers (1)

Rebse
Rebse

Reputation: 10377

Use xmltask combined with xpath, i.e.:

<project>
<!-- Import XMLTask -->
<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask"/>

<macrodef name="grepxml">
 <attribute name="src"/>
 <attribute name="xpath"/>
 <attribute name="result"/>
 <sequential>
  <xmltask source="@{src}">
   <copy path=@{xpath}" property="@{result}"/>
  </xmltask>
 </sequential>
</macrodef>

<grepxml
 src="path/to/your/xml"
 xpath="string(//Month[@name='July']/foo/@*)"
 result="foobar"
/> 

 <echo>$${foobar} => ${foobar}</echo>

</project>

will grep 'zzz'

Upvotes: 2

Related Questions