Change XElement name in linq to xml

I have 2 xmls.SourceXml and TargetXml

I am importing some xml elements in another xml.

That's all good, but some elements I just need to change the name. What I am doing now, I am creating an element from scratch, the only difference is that it is the xml name.

Let me give you an example.

In my original Xml, I have an element named

 <OldBank>
       <SortCode>123456</SortCode>
       <AccountNumber>12345678</AccountNumber>  
       etc....        
 </OldBank>

      

My Target xml should be called NewBank with children element which is exactly the same

  <NewBank>
       <SortCode>123456</SortCode>
       <AccountNumber>12345678</AccountNumber>  
       etc....        
 </NewBank>

      

This is what I am doing:

    public static void ReplaceNewCustomerDetails(this XDocument xDoc)
    {
        XElement oldBankElement = GetOldBankElement(xDoc);

       var newBakXml= new XElement("NewBank",
                     new XElement(oldBankElement.ElementOrDefault("SortCode")),
                     new XElement(oldBankElement.ElementOrDefault("AccountNumber")));

       //Build new xml. This is what I do
       var newXml = new XElement("MyNewXml");
       newXml.Add(newBakXml);

      //I wish I could just change the name of the xml rather then building it again
       var newXml = new XElement("MyNewXml");
       newXml.Add(oldBankElement.Name="NewBank");

      

Any suggestion or more elegant solution

thank

+3


source to share


1 answer


You don't need to create new elements - just pass existing ones:

var newBakXml = new XElement("NewBank", 
                             oldBankElement.Attributes(), 
                             oldBankElement.Elements());
newXml.Add(newBakXml);

      



Or just change the name:

oldBakElement.Name = "NewBank";
newXml.Add(oldBakElement);

      

+6


source







All Articles