xmlproperty and retrieving property value of xml element if specific attribute is present/set

梦想的初衷 提交于 2019-12-22 18:24:23

问题


My Xml looks like:

<root>
        <foo location="bar"/>
        <foo location="in" flag="123"/>
        <foo location="pak"/>
        <foo location="us" flag="256"/>
        <foo location="blah"/>
</root>

For foo xml element flag is optional attribute.

And when I say:

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

 <echo message="foo(location) : ${foo(location)}"/>

prints all locations :

foo(location) : bar,in,pak,us,blah

Is there a way to get locations only if flag is set to some value?


回答1:


Is there a way to get locations only if flag is set to some value?

Not with xmlproperty, no, as that will always conflate values that have the same tag name. But xmltask can do what you need as it supports the full power of XPath:

<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask">
  <classpath path="xmltask.jar" />
</taskdef>

<xmltask source="${base.dir}/build/my.xml">
  <copy path="/root/foo[@flag='123' or @flag='256']/@location"
        property="foo.location"
        append="true" propertySeparator="," />
</xmltask>
<echo>${foo.location}</echo><!-- prints in,us -->

If you absolutely cannot use third-party tasks then I'd probably approach the problem by using a simple XSLT to extract just the bits of the XML that you do want into another file:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:param name="targetFlag" />

  <xsl:template name="ident" match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()" /></xsl:copy>
  </xsl:template>

  <xsl:template match="foo">
    <xsl:if test="@flag = $targetFlag">
      <xsl:call-template name="ident" />
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

Call this with the xslt task

<xslt in="${base.dir}/build/my.xml" out="filtered.xml" style="extract.xsl">
  <param name="targetFlag" expression="123" />
</xslt>

This will create filtered.xml containing just

<root>
        <foo location="in" flag="123"/>
</root>

(modulo changes in whitespace) and you can load this using xmlproperty in the normal way.



来源:https://stackoverflow.com/questions/19545552/xmlproperty-and-retrieving-property-value-of-xml-element-if-specific-attribute-i

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!