使用Ant解析XML文档中的字符串

时间:2012-05-07 17:30:00

标签: xml string ant target

在以下文件中:

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

1 个答案:

答案 0 :(得分:4)

我有一个好消息和一个坏消息。一个坏消息是没有开箱即用的解决方案。好消息是xmlproperty任务是可扩展的,这要归功于将processNode()方法暴露为受保护的方法。这是你可以做的:

1。使用ant.jar创建和编译(你可以在你的ant发​​行版的lib子目录中找到一个,或者在类路径中找到get it from 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子目录 - &gt;将编译后的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

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

相关问题