Ant: Remove multiple lines if keyword match

时间:2016-08-31 17:01:56

标签: ant

I have an XML file which contains the following:

  <feature name="Notification">
        <param name="android-package" value="org.apache.cordova.dialogs.Notification" />
    </feature>    
    <feature name="FileTransfer">
        <param name="android-package" value="org.apache.cordova.filetransfer.FileTransfer" />
    </feature>
    <feature name="Capture">
        <param name="android-package" value="org.apache.cordova.mediacapture.Capture" />
    </feature>
    <feature name="Battery">
        <param name="android-package" value="org.apache.cordova.batterystatus.BatteryListener" />
    </feature>

How can I delete a full <feature> tag based on its name using Ant script?

For example: If "Battery" is found in the xml, delete the following:

<feature name="Battery">
        <param name="android-package" value="org.apache.cordova.batterystatus.BatteryListener" />
    </feature>

1 个答案:

答案 0 :(得分:1)

Ant可以使用XSLT样式表来处理XML文件。

实施例

├── build.xml
├── data.xml
├── process.xsl
└── target
    └── output.xml

的build.xml

<project name="demo" default="build">

    <target name="init">
        <mkdir dir="target"/>
    </target>

    <target name="build" depends="init">
        <xslt style="process.xsl" in="data.xml" out="target/output.xml"/>
    </target>

    <target name="clean">
        <delete dir="target"/>
    </target>

</project>

process.xsl

注意如何使用Xpath表达式过滤掉功能标签名称“Battery”:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml"/>

    <xsl:template match="/data">
        <data>
            <xsl:apply-templates select="feature[@name!='Battery']"/>
        </data>
    </xsl:template>

    <xsl:template match="feature">
        <xsl:copy-of select="."/>
    </xsl:template>

</xsl:stylesheet>

data.xml中

<data>
 <feature name="Notification">
        <param name="android-package" value="org.apache.cordova.dialogs.Notification" />
    </feature>    
    <feature name="FileTransfer">
        <param name="android-package" value="org.apache.cordova.filetransfer.FileTransfer" />
    </feature>
    <feature name="Capture">
        <param name="android-package" value="org.apache.cordova.mediacapture.Capture" />
    </feature>
    <feature name="Battery">
        <param name="android-package" value="org.apache.cordova.batterystatus.BatteryListener" />
    </feature>
</data>

目标/的Output.xml

格式化结果:

<data>
  <feature name="Notification">
    <param name="android-package" value="org.apache.cordova.dialogs.Notification"/>
  </feature>
  <feature name="FileTransfer">
    <param name="android-package" value="org.apache.cordova.filetransfer.FileTransfer"/>
  </feature>
  <feature name="Capture">
    <param name="android-package" value="org.apache.cordova.mediacapture.Capture"/>
  </feature>
</data>