根据顶级元素的属性值检索Xml元素的属性值

时间:2013-11-07 10:20:23

标签: xml ant

我的示例Xml看起来像:

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

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

</root>

当我说:

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

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

打印我 bar,zzz 。我想根据月份名称检索foo xml元素的someAttr值。例如,让我Month.foo(someAttr) where Month.name="Jan"

Ant中是否有一种方式,或者我应该根据另一个相关查询使用xslt定义我的规则:xmlproperty and retrieving property value of xml element if specific attribute is present/set

1 个答案:

答案 0 :(得分:2)

使用xmltask结合xpath,即:

<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>

将grep'zzz'