Parsing a String in an XML Document Using Ant

In the following document:

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

How to return a value: id17

When I run the following target in my Ant file:

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

I get -

print:
        [echo] name = section,id17

Is there a way to indicate that I only need the id resource?

+3
source share
1 answer

I had good news and bad news for you. The bad news is that there is no turnkey solution. The good news is that the task xmlpropertyis quite extensible due to the fact that you expose the method processNode()protected. Here is what you can do:

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 script → MyXmlProp task, - : task/pl/sobczyk/peter/MyXmlProp.class.

3. ant script, - :

<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

, , - :-). , :). .

+4

All Articles