Search code examples
c#asp.netxmldocument

XML Rename all child elements to the same tag name


I have the following XML document structure.

<FareSearchResponse>
    <AirlineList>
        <AQR>...</AQR>
        <ABA>...</ABA>
        <AAI>...</AAI>
        <A9W>...</A9W>
        <AVS>...</AVS>
        <AAF>...</AAF>
        <AEY>...</AEY>
        <ALH>...</ALH>
        <AQF>...</AQF>
    </AirlineList>
</FareSearchResponse>

I want to rename all child elements of AirlineList to Airline. The child name tags vary and can be any name. So there is no way of knowing which name tags will appear and what they will be. It is a dynamic XML document from a web service. So far I have managed to load the XML string into an XmlDocument;

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(System.Web.HttpUtility.HtmlDecode(resultString));
XElement firstChild = xmlDoc.ToXDocument().Root.Elements().First();

I want to select all AirlineList elements and rename them to Airline.

I have added a more details. The XML document is now contained in firstChild. How do I replace elements in the firstChild and not directly from XmlDocument

Thanks.


Solution

  • I want to select all AirlineList elements and rename them to Airline.

    Use Linq to Xml and update the Name for child elements.

    var doc = XDocument.Load(filepath);
    
    foreach (var element in doc.Descendants("AirlineList").Elements())
    {
        element.Name ="Airline";
    }
    

    Check this example