使用Ant任务编辑XML

4

我试图使用ant任务编辑我的config.xml文件,但我无法做到这一点,有人能告诉我如何使用ant任务自动地编辑xml,以便我不需要为每个新分支手动更改它吗?


你能否在你的问题中添加更多细节?这将使得回答更具体。 - martin clayton
3个回答

1

1

我使用了Groovy来完成这个任务。Groovy非常类似于Java,因此您可以创建与静态Java方法非常相似的Groovy类,并使用<groovy>任务让ant调用您的Groovy脚本(当然,您需要包含Groovy任务定义)。

由于Groovy可以使用Java语法,因此您可以包括org.w3c.com.*库以访问DOM类。

例如,以下是代码片段,显示将资源引用元素添加到指定的web.xml文件:

import org.w3c.dom.*;

String web_xml_filename=args[0];
String res_ref_name=args[1];
Document doc = DomHelper.getDoc(web_xml_filename);
Element rootNode=doc.getDocumentElement();
newNode = doc.createElement("resource-ref"); 
DomHelper.createElement(doc, newNode, "res-ref-name", res_ref_name);
DomHelper.createElement(doc, newNode, "res-type", "javax.sql.DataSource");
DomHelper.createElement(doc, newNode, "description", description);
DomHelper.createElement(doc, newNode, "res-auth", "Container");
rootNode.insertBefore(newNode, nodes.item(0));
DomHelper.writeDoc(doc, web_xml_filename, false);

要从Ant中调用,请使用Groovy任务:

<groovy src="${e5ahr-groovy.dir}/addResoureRefToJBossWebXML.groovy" classpath="${groovy.dir}">
    <arg value="${jboss-web.xml}"/>
    <arg value="jdbc/somesource/>
    <arg value="java:jdbc/somesource"/>
</groovy>

0
你可以使用ReplaceRegExp。Pattern和Expression选项不能让你使用少于或多于,但可以用HTML实体替换。例如:
<replaceregexp byline="true">
    <!-- In config.xml this looks like <myVariable></myVariable> -->
    <regexp pattern="&lt;myVariable&gt;(.*)&lt;/myVariable&gt;" />
    <substitution expression="&lt;myVariable&gt;${myVariable.value}&lt;/myVariable&gt;" />
        <fileset dir="${user.dir}">
            <include name="config.xml" />
        </fileset>
</replaceregexp>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接