3

在以下文档中:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="toc">section</string>
<string name="id">id17</string>
</resources>

如何返回值:id17

当我在我的 Ant 文件中运行以下目标时:

  <target name="print"
    description="print the contents of the config.xml file in various ways" >

  <xmlproperty file="$config.xml" prefix="build"/>
  <echo message="name = ${build.resources.string}"/>
  </target>

我得到 -

print:
        [echo] name = section,id17

有没有办法指定我只想要资源“id”?

4

1 回答 1

4

我有一个好消息和一个坏消息要告诉你。一个坏消息是没有开箱即用的解决方案。好消息是,由于将方法公开为受保护的,因此该xmlproperty任务非常可扩展。processNode()以下是您可以执行的操作:

1. 在类路径上使用 ant.jar(您可以lib在您的 ant 发行版的子目录中找到或从 Maven 获取)创建并编译以下代码:

package pl.sobczyk.piotr;

import org.apache.tools.ant.taskdefs.XmlProperty;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class MyXmlProp extends XmlProperty{

@Override
public Object processNode(Node node, String prefix, Object container) {
    if(node.hasAttributes()){
        NamedNodeMap nodeAttributes = node.getAttributes();
        Node nameNode = nodeAttributes.getNamedItem("name");
        if(nameNode != null){
           String name = nameNode.getNodeValue();

           String value = node.getTextContent();
           if(!value.trim().isEmpty()){
               String propName = prefix + "[" + name + "]";
               getProject().setProperty(propName, value);
           }
       }
    }

    return super.processNode(node, prefix, container);
}

}

2. 现在你只需要让这个任务对 ant 可见。task最简单的方法:在您拥有 ant 脚本的目录中创建子目录 -> 将已编译的 MyXmlProp 类及其目录结构复制到task目录,因此您最终应该得到类似:task/pl/sobczyk/peter/MyXmlProp.class.

3. 将任务导入到您的 ant 脚本中,您最终应该得到如下内容:

<target name="print">
  <taskdef name="myxmlproperty" classname="pl.sobczyk.piotr.MyXmlProp">
    <classpath>
      <pathelement location="task"/>
    </classpath>
  </taskdef>
  <myxmlproperty file="config.xml" prefix="build"/>
  <echo message="name = ${build.resources.string[id]}"/>
</target>

4. 运行 ant,ant voila,你应该看到:[echo] name = id17

我们在这里所做的是为您的特定情况定义一个特殊的花哨的方括号语法:-)。对于一些更通用的解决方案,任务扩展可能会稍微复杂一些,但一切皆有可能:)。祝你好运。

于 2012-05-07T21:39:15.827 回答