【问题标题】:Parsing a string within an XML document using Ant使用 Ant 解析 XML 文档中的字符串
【发布时间】:2012-05-07 17:29:59
【问题描述】:

在以下文档中:

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

【问题讨论】:

    标签: xml string ant target


    【解决方案1】:

    我有一个好消息和一个坏消息要告诉你。一个坏消息是没有开箱即用的解决方案。好消息是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 可见。最简单的方法:在您拥有 ant 脚本的目录中创建 task 子目录 -> 将已编译的 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。运行蚂蚁,蚂蚁瞧,你应该看到:[echo] name = id17

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

    【讨论】:

    • 感谢您的详细回复。我会发回结果。
    • 正是我想要的! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    相关资源
    最近更新 更多