Update xml elements with specific id in gradle

2020-05-06 14:03发布

问题:

I want to make the following changes in the xml file

My test.xml

<root>
    <display-name>Some Name</display-name>
    ....
    <resource-ref id='change'>
        <resource-name>Change this</resource-name>
    </resource-ref>
    <resource-ref id='modify'>
        <resource-name>Change this too</resource-name>
    </resource-ref>
</root>

I want to make changes in this xml file to look like this

<root>
    <display-name>Final Name</display-name>
    ....
    <resource-ref id='change'>
        <resource-name>After Change</resource-name>
    </resource-ref>
    <resource-ref id='modify'>
        <resource-name>After Modify</resource-name>
    </resource-ref>
</root>

The first answer in this question nearly answers my question. But I need to make specific changes for elements with specific id as you can see.

This looks very simple. I tried looking answers and failed to find. Any help is appreciated.

And btw my gradle script looks like this

task ("replace")<<{
def xmlSource = file(path/to/test.xml)
def xmlDest = file(path/to/destination)
def xmlParser = new XmlParser()
xmlParser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false)
def xmlRoot = xmlParser.parse(xmlSource)

xmlRoot.'display-name'[0].value = 'RTM16'
//Looking for something like this
//xmlRoot.'resource-ref'[@id='change'].'resource-name'[0].value = 'After Change'
//xmlRoot.'resource-ref'[@id='modify'].'resource-name'[0].value = 'After Modify'

def nodePrinter = new XmlNodePrinter(new PrintWriter(new FileWriter(xmlDest)))
nodePrinter.preserveWhitespace = true
nodePrinter.print(xmlRoot)
}

回答1:

After going through the Node (Groovy 2.4.6) I came up with this

task ("replace")<<{
xmlSource = file(path/to/xml source file)
xmlDest = file(path/to/destinationfile)
def parser = new XmlParser()
def xmlRoot = parser.parse(xmlSource)
xmlRoot.each{
    if(it.name().equals("resource-ref")&& it.@id.equals("change")){
        it.'resource-name'[0].value = 'After Change'
    }
    else if(it.name().equals("resource-ref")&& it.@id.equals("modify")){
        it.'resource-name'[0].value = 'After Modify'
    }
}

def b = new XmlNodePrinter(new PrintWriter(new FileWriter(xmlDest)))
b.preserveWhitespace = true
b.print(z)
}

Not sure if its the best way. But it works



标签: gradle groovy