ant中匹配xml内容并替换,匹配换行

本文介绍如何使用Ant的replaceregxp任务来修改AndroidManifest.xml文件中的application节点名称,并添加新的meta-data标签。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ant 中的 replaceregexp 正则表达式替换,可以在我们对项目构建的时候,替换处理各种格式的文件内容。

有如下 AndroidManifest.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shanhy.example.packers"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="false"
        android:name="com.shanhy.example.packers.MyApplication"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


现在有需求:

1) 需要替换 application 中的 android:name 属性的内容为 com.shanhy.example.packers.ShellApplication

2) 并且在 application 节点后面添加一段代码 <meta-data android:name="APPLICATION_CLASS_NAME" android:value="com.shanhy.example.packers.MyApplication" />  其中属性 value 的值为 application 的 android:name 属性替换之前的值。

实现脚本如下:

<!--处理AndroidManifest.xml文件-->
<target name="modify-manifest" depends="clean-resource,copy-resource">
<loadfile property="manifest.content"
     srcFile="${basedir}/AndroidManifest.xml"
     failonerror="true"/>

<!-- 提取实际运行程序的applicationName -->
<propertyregex property="manifest.application.name" 
input="${manifest.content}" 
regexp="&lt;application([^..]*)android:name=&quot;(\S*)&quot;([^..]*)&gt;" 
select="\2" 
casesensitive="true" />
<echo>${manifest.application.name} >>>> ${shellApplication}</echo>

<!-- 修改application节点的android:name属性-->
<replaceregexp flags="g" byline="false">
<regexp pattern="&lt;application([^..]*)android:name=&quot;(\S*)&quot;([^..]*)&gt;" />
<substitution expression="&lt;application\1android:name=&quot;${shellApplication}&quot;\3&gt;" />
<fileset dir="${basedir}" includes="AndroidManifest.xml" />
</replaceregexp>

<!-- 在application节点下增加meta-data标签 -->
<replaceregexp flags="g" byline="false">
<regexp pattern="&lt;application([^&gt;]*)&gt;" />
<substitution expression="&lt;application\1&gt;&#10;&#10;&#9;&#9;&lt;meta-data android:name=&quot;APPLICATION_CLASS_NAME&quot; android:value=&quot;${manifest.application.name}&quot; /&gt;&#10;" />
<fileset dir="${basedir}" includes="AndroidManifest.xml" />
</replaceregexp>
</target>



-----------------------------

(完)





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值