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 ?

4
  • 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. Commented Mar 9, 2021 at 11:26
  • Does this answer your question? How does one parse XML files? Commented Mar 9, 2021 at 11:30
  • Does this answer your question? Change the node names in an XML file using C# Commented Mar 9, 2021 at 12:06
  • 1
    XML should be well-formed. It is better to use XSLT for such scenario. Commented Mar 9, 2021 at 14:38

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.