Change the name of an XElement in linq to xml

2019-05-06 23:36发布

问题:

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

回答1:

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);


标签: linq-to-xml