Search code examples
c#xmlxmldocumentxslt

Changing the Format of XML


I have the following Xml :

<Root>
  <Username>
    <string>Fred</string>
    <string>John</string>
  </Username>
</Root>

What I need is a Xml formatted like this:

 <Root>
    <Username>Fred</Username>
    <Username>John</Username>
 </Root>

Is there a way to achieved that?


Solution

  • Linq-to-XML:

    using System.Linq;
    using System.Xml.Linq;
    
    var indoc = XDocument.Load("c:\\test.xml");   
    var outdoc = new XDocument(
                  new XElement("Root", 
                    indoc.Descendants("Root")
                         .Descendants("Username")
                         .Elements()
                         .Select(n => n.Value)
                         .Select(i => new XElement("Username", i))));
    
    // TODO: Save doc using doc.WriteTo(xmlWriter) to the file