-2

I need to update xml file with adding 2 to the value but within different tag

eg: data.xml

<?xml version="1.0"?>
<data>
   <tag1>2</tag1>
   <tag2>6</tag2>
   <tag10>7</tag10>
   <string>nochange_string</string>
</data>

to updated_data.xml

<?xml version="1.0"?>
<newdata>
   <tag1>4</tag1>
   <tag2>8</tag2>
   <tag10>9</tag10>
   <string>nochange_string</string>
</newdata>

I am aware that I would need to call a method to add 2 to each tag except last 'string' tag but I am stuck to keep the tag# as it was but everything should be in the different tag called 'newdata'. How would I do this? Thanks in advance!

  • 1
    You should be able to use the built-in Java DOM Parser. Documentation is found here: https://docs.oracle.com/javase/tutorial/jaxp/dom/readingXML.html and a somewhat related question that might give you a couple ideas: https://stackoverflow.com/questions/31693670/how-to-update-xml-files-in-java. – purple Jul 25 '21 at 03:37
  • 1
    Why not to use XSLT for such task? – Yitzhak Khabinsky Jul 25 '21 at 03:55

1 Answers1

1

A method by using XSLT makes it simple.

Input XML

<?xml version="1.0"?>
<data>
    <tag1>2</tag1>
    <tag2>6</tag2>
    <tag10>7</tag10>
    <string>nochange_string</string>
</data>

XSLT

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="no"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/data">
        <newdata>
            <xsl:apply-templates select="@*|node()"/>
        </newdata>
    </xsl:template>

    <xsl:template match="*[starts-with(local-name(), 'tag')]">
        <xsl:copy>
            <xsl:value-of select=". + 2"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Output XML

<?xml version='1.0' encoding='utf-8' ?>
<newdata>
  <tag1>4</tag1>
  <tag2>8</tag2>
  <tag10>9</tag10>
  <string>nochange_string</string>
</newdata>
Yitzhak Khabinsky
  • 18,471
  • 2
  • 15
  • 21
  • You missed that he/she also wants to rename `data` as `newdata`. But actually that illustrates why doing it in XSLT is such a good idea, it's very easy to add one more rule as the requirements evolve. – Michael Kay Jul 25 '21 at 10:05
  • @MichaelKay, Eagle eyes. Thanks. I updated the answer. – Yitzhak Khabinsky Jul 25 '21 at 14:46