xmlparsingscriptingxml-parsingcustomtool

Parsing and altering xml file with custom tool or script


I bump into something like this quite often. This time I have sprite sheet file containing lots of lines like this:

<textureregion id="2" src="blue_ship1.png" x="778" y="791" width="64" height="65" rotated="false" trimmed="false" srcx="0" srcy="0" srcwidth="64" srcheight="65"/>

Now I would need to increment the id on each textureregion by for example 100 and then write the same xml to another file or overwrite the existing. I will have to do this again and again so I need to automate it. I can think of countless of ways to go about this. But I also want to learn something new so, here goes:

How would you complete such a task? Write a custom tool? Script? What language, library or tool would you use? What's the least amount of lines or work you could have this sorted in?


Solution

  • You can use xmlstarlet to edit a xml file.
    For example: id ==> id+100

    $ xmlstarlet edit --update '/textureregion/@id' -x '.+100'  input.xml
    <?xml version="1.0"?>
    <textureregion id="102" src="blue_ship1.png" x="778" y="791" width="64" height="65" rotated="false" trimmed="false" srcx="0" srcy="0" srcwidth="64" srcheight="65"/>
    

    You can add --inplace option to edit file inplace.