简体   繁体   中英

Ant - how to scan file and get last specific occurrence of text

I have a big.xml file in the form:

<items>
  <item from="" to="" version="">
    <subAttribute1>A</subAttribute1>
    <subAttribute2>B</subAttribute2>
  </item>
  <item from="" to="" version="">
    <subAttribute1>C</subAttribute1>
    <subAttribute2>D</subAttribute2>
  </item>
</items>

is there a way in ant where I can:

  • look for / load the file
  • get the latest to attribute among the list of item?

EDIT:

I can load the xml using the following:

<xmlproperty file="$myXMLFile.xml" collapseAttributes="true" keepRoot="false"/>

and by adding the following targets I can scan the file:

    <target name="for-each" depends="compile">
        <echo>for each test</echo>
        <foreach list="${item.to}" target="loop" param="var" delimiter=","/>
    </target>

    <target name="loop">
        <echo>inside loop</echo>
        <echo message="To :: ${var}"/>
    </target>

Thanks

If I understand what you need, maybe you can adapt this.

Given this input file (source.xml) similar to your example:

<?xml version="1.0" encoding="UTF-8"?>
<items>
  <item from="" to="not-last-to" version="first-one">
    <subAttribute1>A</subAttribute1>
    <subAttribute2>B</subAttribute2>
  </item>
  <item from="" to="not-last-to" version="second-one">
    <subAttribute1>A2</subAttribute1>
    <subAttribute2>B2</subAttribute2>
  </item>
  <item from="" to="last-to" version="last-one">
    <subAttribute1>C</subAttribute1>
    <subAttribute2>D</subAttribute2>
  </item>
</items>

This buildfile:

<project name="ant" > 
  <xslt in="source.xml" out="last-to.txt" style="style.xsl" /> 
  <loadproperties srcFile="last-to.txt" />
  <echo message="Last 'To' :: ${last-to}" />
</project> 

And this XSLT stylesheet, style.xsl (I cobbled this together, don't assume any best practice in here:):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
<xsl:output method="text"/> 
  <xsl:template match="item"> 
    <xsl:apply-templates select="item"></xsl:apply-templates>
  </xsl:template> 
  <xsl:template match="item[last()]"> 
    <xsl:apply-templates select="item">last-to:<xsl:value-of select="@to"/>
    </xsl:apply-templates>
  </xsl:template> 
</xsl:stylesheet>

Running Ant produces:

[echo] Last 'To' :: last-to

The idea is to use an XSLT stylesheet to fish out the element you need, save it to a file in Ant properties format, then read that file into the build.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM