Ant and XML configuration file parsing

2019-02-18 10:00发布

I have an XML file of the following form -

<map MAP_XML_VERSION="1.0">
    <entry key="database.user" value="user1"/>
    ...
</map>

Does ant have a native ability to read this and let me perform an xquery to pull back values for keys? Going through the API I did not see such capabilities.

标签: java xml ant
3条回答
一夜七次
2楼-- · 2019-02-18 10:09

You can use the scriptdef tag to create a JavaScript wrapper for your class. Inside JS, you pretty much have the full power of Java and can do any kind of complicated XML parsing you want.

For example:

<project default="build">        
    <target name="build">            
        <xpath-query query="//entry[@key='database.user']/@value"
                     xmlFile="test.xml" addproperty="value"/>
        <echo message="Value is ${value}"/>    
    </target>

    <scriptdef name="xpath-query" language="javascript">
        <attribute name="query"/>
        <attribute name="xmlfile"/>
        <attribute name="addproperty"/>

        <![CDATA[
            importClass(java.io.FileInputStream);
            importClass(javax.xml.xpath.XPath);
            importClass(javax.xml.xpath.XPathConstants);
            importClass(javax.xml.xpath.XPathFactory);
            importClass(org.xml.sax.InputSource);

            var exp = attributes.get("query");
            var filename = attributes.get("xmlfile");
            var input = new InputSource(new FileInputStream(filename));
            var xpath = XPathFactory.newInstance().newXPath();
            var value = xpath.evaluate(exp, input, XPathConstants.STRING);

            self.project.setProperty( attributes.get("addproperty"), value );

        ]]>

    </scriptdef>
</project>
查看更多
The star\"
3楼-- · 2019-02-18 10:09

Sounds like you want something like ant-xpath-task. I'm not aware of a built-in way to do this with Ant.

查看更多
聊天终结者
4楼-- · 2019-02-18 10:17

The optional Ant task XMLTask is designed to do this. Give it an XPath expression and you can select the above into (say) a property. Here's an article on how to use it, with examples. It'll do tons of other XML-related manipulations/querying/creation as well.

e.g.

<xmltask source="map.xml">
   <!-- copies to a property 'user' -->
   <copy path="/map/entry[@key='database.user']/@value" attrValue="true" property="user"/>
</xmltask>

Disclaimer: I'm the author.

查看更多
登录 后发表回答