Ant xmlproperty task. What happens when there is m

2019-02-17 12:18发布

问题:

I am trying to follow a large ant buildfile that I have been given, and I am having trouble understanding the functionality of xmlproperty in this case. Consider this xml file, example.xml.

<main>
  <tagList>
    <tag>
      <file>file1</file>
      <machine>machine1</machine>
    </tag>
    <tag>
      <file>file2</file>
      <machine>machine2</machine>
    </tag>
  </tagList>
</main>

In the buildfile, there is a task which can be simplified to the following for this example:

<xmlproperty file="example.xml" prefix="PREFIX" />

As I understand it, if there was only one <tag> element, I could get the contents of <file> with ${PREFIX.main.tagList.tag.file} because it is roughly equivalent to writing this:

<property name="PREFIX.main.tagList.tag.file" value="file1"/>

But as there are two <tag>s, what is the value of ${PREFIX.main.tagList.tag.file} in this case? If it is some sort of list, how do I iterate through both <file> values?

I am using ant 1.6.2.

回答1:

When multiple elements have the same name, <xmlproperty> creates a property with comma-separated values:

<project name="ant-xmlproperty-with-multiple-matching-elements" default="run" basedir=".">
    <target name="run">
        <xmlproperty file="example.xml" prefix="PREFIX" />

        <echo>${PREFIX.main.tagList.tag.file}</echo>
    </target>
</project>

The result:

run:
     [echo] file1,file2

To process the comma-separated values, consider using the <for> task from the third-party Ant-Contrib library:

<project 
    name="ant-xmlproperty-with-multiple-matching-elements" 
    default="run" 
    basedir="." 
    xmlns:ac="antlib:net.sf.antcontrib"
    >
    <taskdef resource="net/sf/antcontrib/antlib.xml" />
    <target name="run">
        <xmlproperty file="example.xml" prefix="PREFIX" />

        <ac:for list="${PREFIX.main.tagList.tag.file}" param="file">
            <sequential>
                <echo>@{file}</echo>
            </sequential>
        </ac:for>
    </target>
</project>

The result:

run:
     [echo] file1
     [echo] file2


标签: xml ant