如果存在/设置特定属性,则 xmlproperty 和检索 xml 元素的属性值 [英] xmlproperty and retrieving property value of xml element if specific attribute is present/set

查看:28
本文介绍了如果存在/设置特定属性,则 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.

这篇关于如果存在/设置特定属性,则 xmlproperty 和检索 xml 元素的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆