Change ALL Tag Name to Lowercase inside XMLDocument

I need to change ALL the Tag name to Lowercase but leave the InnerText or Value as it is. I just found the thread showing how to change the casing for the entire document but NOT just for the Tag names.

Code

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlDoc.OuterXml.ToLower());

2 answers

  • answered 2019-05-15 03:23 flyte

    You can try something like this:

    var doc = XDocument.Load(filepath);
    foreach (var element in doc.Descendants().Elements())
    {
        element.Name = element.Name.LocalName.ToLower();
    }
    

  • answered 2019-05-15 04:35 Daniel

    Original.xml

    <?xml version="1.0" encoding="utf-8" ?>
    <ROOT>
      <InNeRtAg>SoMe TeXt</InNeRtAg>
      <NeStEdElEmEnT>
        <InNeRnEsTiNg>SoMe TeXt</InNeRnEsTiNg>
      </NeStEdElEmEnT>
    </ROOT>
    

    Changing ALL nodes including the root element:

    var doc = XDocument.Load("Original.xml");
    
    // also need to change the root element
    doc.Root.Name = doc.Root.Name.LocalName.ToLower();
    
    foreach (var element in doc.Descendants().Elements())
    {
        element.Name = element.Name.LocalName.ToLower();
    }
    
    doc.Save("Modified.xml");
    

    Results in Modified.xml

    <?xml version="1.0" encoding="utf-8"?>
    <root>
      <innertag>SoMe TeXt</innertag>
      <nestedelement>
        <innernesting>SoMe TeXt</innernesting>
      </nestedelement>
    </root>
    

    When using

    foreach (var element in doc.Descendants().Elements())
    {
        element.Name = element.Name.LocalName.ToLower();
    }
    

    the root element will not be changed.

    <?xml version="1.0" encoding="utf-8"?>
    <ROOT>
      <innertag>SoMe TeXt</innertag>
      <nestedelement>
        <innernesting>SoMe TeXt</innernesting>
      </nestedelement>
    </ROOT>