如果存在/设置特定属性,则 xmlproperty 和检索 xml 元素的属性值

问题描述:

我的 Xml 看起来像:

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>

对于 foo xml 元素标志是可选属性.

For foo xml element flag is optional attribute.

当我说:

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

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

打印所有位置:

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

有没有办法仅在标志设置为某个值时获取位置?

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

有没有办法仅在标志设置为某个值时获取位置?

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

不与 xmlproperty 一起使用,不,因为这将始终混淆具有相同标记名称的值.但是 xmltask 可以满足您的需求,因为它支持 XPath 的全部功能:

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

如果您绝对不能使用第三方任务,那么我可能会使用一个简单的 XSLT 来解决这个问题,以将您确实想要的 XML 部分提取到另一个文件中:>

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>

xslt 任务调用这个

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

这将创建 filtered.xml 只包含

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

(空格中的模数变化),您可以使用 xmlproperty 以正常方式加载它.

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