I am having trouble renaming XML element names. I'm attempting to achieve the following.
Input:
<Addresses>
<AddressItem>
<AddressLine1>RZN850PXKYG</AddressLine1>
<AddressLine2>RYK57IT7Y9Z</AddressLine2>
<AddressType>Physical</AddressType>
<City>Some City</City>
<PostalCode>9999</PostalCode>
<Province>Some Province</Province>
<Suburb>Some Suburb</Suburb>
</AddressItem>
</Addresses>
Expected output:
<b:Addresses>
<b:AddressItem>
<b:AddressLine1>RZN850PXKYG</b:AddressLine1>
<b:AddressLine2>RYK57IT7Y9Z</b:AddressLine1>
<b:AddressType>Physical</b:AddressType>
<b:City>Some City</b:City>
<b:PostalCode>9999</b:PostalCode>
<b:Province>Some Province</b:Province>
<b:Suburb>Some Suburb</b:Suburb>
</b:AddressItem>
</b:Addresses>
Previously I have successfully added attributes and renamed elements using something similar to this:
var xmlDoc = XDocument.Parse(requestObj);
foreach (var element in xmlDoc.Descendants())
{
if (element.Name.LocalName.StartsWith("something"))
{
//example rename element
element.Name = "request";
XNamespace b = "http://schemas.something.org/bla/07/WebServices.Stuff";
XNamespace i = "http://www.w3.org/2001/XMLSchema-instance";
//set it's attributes
element.SetAttributeValue(XNamespace.Xmlns + "b", b);
element.SetAttributeValue(XNamespace.Xmlns + "i", i);
}
}
I have attempted to achieve my expected result by simply using the below code but the colon is giving me problems it seems:
foreach (var element in xmlDoc.Descendants())
{
element.Name = "b:" + element.Name;
}
I have searched using the error message received (System.Xml.XmlException: 'The ':' character, hexadecimal value 0x3A, cannot be included in a name.'
) but none of the solutions seems applicable to elements needing to be renamed recursively.