0

I have an XML file with :

<IMG0></IMG0>
<IMG1></IMG1>
<IMG2></IMG2>

It represents up to 10 images.

I try to delete the number for having :

<IMG></IMG>
<IMG></IMG>
<IMG></IMG>

I make :

for (int l = 0; l <= 10; l++)
{
      doc.InnerXml.Replace("IMG" + l, "IMG");
}

"doc" is an XMLDocument.

But the node doesn't change.

What can I do ?

  • 1
    For one, you aren't assigning the result of the `Replace` operation anywhere, so that loop essentially modifies strings and throws them away. Secondly, that will also break any image that might be called e.g. `IMG0030.jpg`, since a string replacement operation doesn't discriminate between tags and text. You should traverse the XML tree and fix the node names there. – AKX Mar 09 '21 at 11:26
  • Does this answer your question? [How does one parse XML files?](https://stackoverflow.com/questions/55828/how-does-one-parse-xml-files) – Sinatr Mar 09 '21 at 11:30
  • Does this answer your question? [Change the node names in an XML file using C#](https://stackoverflow.com/questions/475293/change-the-node-names-in-an-xml-file-using-c-sharp) – Peter Csala Mar 09 '21 at 12:06
  • 1
    XML should be **well-formed**. It is better to use XSLT for such scenario. – Yitzhak Khabinsky Mar 09 '21 at 14:38

1 Answers1

0

By using XSLT and Identity Transform pattern.

The 2nd template will find any XML element that starts with 'IMG' and transform it to just 'IMG' while keeping everyhing else as-is intact.

XML

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <Betalningsmottagares_x0020_postnr>401 01</Betalningsmottagares_x0020_postnr>
   <Betalningsmottagares_x0020_postort>Göteborg</Betalningsmottagares_x0020_postort>
   <IMG0>10</IMG0>
   <IMG1>20</IMG1>
   <IMG2>30</IMG2>
</root>

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="*[starts-with(local-name(), 'IMG')]">
        <IMG>
            <xsl:value-of select="."/>
        </IMG>
        <xsl:apply-templates/>
    </xsl:template>
</xsl:stylesheet>

Output

<?xml version='1.0' encoding='utf-8' ?>
<root>
  <Betalningsmottagares_x0020_postnr>401 01</Betalningsmottagares_x0020_postnr>
  <Betalningsmottagares_x0020_postort>Göteborg</Betalningsmottagares_x0020_postort>
  <IMG>10</IMG>10
  <IMG>20</IMG>20
  <IMG>30</IMG>30
</root>
Yitzhak Khabinsky
  • 18,471
  • 2
  • 15
  • 21