如何在<macrodef>中<foreach>?</macrodef> </foreach>

时间:2013-01-22 11:18:41

标签: ant ant-contrib macrodef

我有一个xml,如下所示:

<data>

    <foo>value1</foo>

    <foo>value2</foo>

    <foo>value3</foo>

  </data>

我想创建实现以下功能的macrodef:

<?xml version="1.0"?>
<project name="OATS" default="execute" basedir=".">

  <xmlproperty file="data.xml" collapseAttributes="true"/>
  <target name="execute">
    <foreach list="${data.foo}" target="runScript" param="script"/>
  </target>
  <target name="runScript">
    <echo>Doing things with ${script}</echo>
  </target>
</project>

有谁知道怎么做?提前谢谢。

3 个答案:

答案 0 :(得分:3)

xmltask是Ant社区中用于此目的的最佳选择,您无需定义自己的macrodef。

例如:

  <tools:xmltask source="data.xml" report="false" >
    <tools:call path="data/foo">
      <param name="value" path="text()"/>
      <actions>
          <echo>Doing things with @{value}</echo>
      </actions>
    </tools:call>
  </tools:xmltask>

我鼓励您阅读用户手册,因为xmltask有很多选项。它基本上支持XPath来提取和迭代xml的任何部分。除了匿名代码块之外,它还支持对现有目标的调用(如示例所示)。

这很难被击败。

答案 1 :(得分:0)

以下示例使用groovy ANT task

<project name="OATS" default="execute" basedir=".">

    <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy">
        <classpath>
            <pathelement location="lib/groovy-all-2.1.0-rc-2.jar"/>
        </classpath>
    </taskdef>

    <target name="execute">
        <groovy>
            def data = new XmlSlurper().parse(new File("data.xml"))

            data.foo.each {
                properties["script"] = it
                ant.project.executeTarget("runScript")
            }
        </groovy>
    </target>

    <target name="runScript">
        <echo>Doing things with ${script}</echo>
    </target>

</project>

答案 2 :(得分:0)

这是我的macrodef。

    <?xml version="1.0" encoding="UTF-8"?>
    <project name="OATS" default="test" basedir=".">
        <property environment = "env"/>
      <path id = "antcontrib.path">
        <fileset file = "${env.ANT_HOME}/../net.sf.antcontrib_1.1.0.0_1-0b2/lib/ant-contrib.jar"/>
      </path>
      <taskdef resource="net/sf/antcontrib/antlib.xml" classpathref="antcontrib.path"/>
      <macrodef name="runOATS">
            <attribute name="suite"/>
            <attribute name="toDir"/>
            <sequential>
                <delete dir="@{toDir}"/>
                <mkdir dir="@{toDir}"/>
                <xmlproperty file="@{suite}" collapseAttributes="true"/>
                <for list="${data.foo}" param="script">
                    <sequential>
                        <runScript script="@{script}"/>
                    </sequential>
                </for>
            </sequential>
        </macrodef>             
        <macrodef name="runScript">
            <attribute name="script"/>
            <sequential>
                <echo>Doing things with @{script}</echo>
            </sequential>
        </macrodef>
        <target name="test">
            <runOATS toDir="/OATS/results" suite="data.xml"/>
        </target>
 </project>