[Fork] https://stackoverflow.com/questions/58172978/renaming-xdocument-element-names

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Data;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;

using NUnit.Framework; //NUnit.Framework.AssertionException

//https://stackoverflow.com/questions/58172978/renaming-xdocument-element-names?noredirect=1#comment102736143_58172978

    public class TestClass
    {
        public static void Test()
        {
			var requestObj = GetXml();
			
			var xmlDoc = XDocument.Parse(requestObj);
			
			XNamespace newNamespace = "http://schemas.something.org/bla/07/WebServices.Stuff";
			
			// Move Addresses elements and children into the new namespace
			foreach (var e in xmlDoc.Descendants().Where(a => a.Name.LocalName == "Addresses").SelectMany(a => a.DescendantsAndSelf()))
			{
				e.Name = newNamespace + e.Name.LocalName;
			}
			
			Console.WriteLine(xmlDoc);
        }
		
		static string GetXml()
		{
			var xml = @"<root><SubElement>
<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>			
</SubElement></root>";
			return xml;
		}
    }

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Roslyn Compiler; Environment version: " + Environment.Version);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Uncaught exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}
;