xmlproperty and retrieving property value of xml e

2019-05-28 09:36发布

问题:

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.



标签: ant