Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the name of an XElement in linq to xml

Tags:

linq-to-xml

I have 2 xmls.SourceXml and TargetXml

I am importing some elements of an xml into another xml.

That is all good however Some Elements I just need to change the name. What I am currently doing I am building the element from scratch with the only difference is the name of the xml.

Let me give you an example.

In my Source Xml I have an element called

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

In My Target xml should be called NewBank with the children element that are exactly the same

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

This is what I do:

    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

Thanks

like image 400
user9969 Avatar asked Jan 27 '13 07:01

user9969


1 Answers

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

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

Or simply change name:

oldBankElement.Name = "NewBank";
newXml.Add(oldBankElement);
like image 142
Sergey Berezovskiy Avatar answered Nov 09 '22 09:11

Sergey Berezovskiy