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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With