using System.Collections.Generic;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;
public static class XObjectExtensions
public static XElement CreateAndAddInRootDefaultNamespace(this XElement parent, string localName)
throw new ArgumentNullException();
var doc = parent.Document;
if (doc == null || doc.Root == null)
throw new ArgumentException(string.Format("No root element found for {0}", parent.Name));
var element = new XElement(doc.Root.GetDefaultNamespace() + localName);
public static void Test()
var xdoc = XDocument.Parse(GetXml());
xdoc.Root.CreateAndAddInRootDefaultNamespace("element");
xdoc.Root.CreateAndAddInRootDefaultNamespace("anotherElement")
.CreateAndAddInRootDefaultNamespace("someNestedElement")
.Add("Some text content");
var xml = @"<root xmlns=""https://stackoverflow.com/questions/55914228/how-do-i-declare-a-xdocument-namespace-globally-in-c"" attr1=""attribute one"" attr2=""attribute two"">
<title>this is the root</title>
<p style=""first""><em>hello</em> world!</p>
public static class XmlSerializationHelper
public static T LoadFromXml<T>(this string xmlString, XmlSerializer serial = null)
serial = serial ?? new XmlSerializer(typeof(T));
using (var reader = new StringReader(xmlString))
return (T)serial.Deserialize(reader);
public static string GetXml<T>(this T obj, bool omitStandardNamespaces)
return obj.GetXml(null, omitStandardNamespaces);
public static string GetXml<T>(this T obj, XmlSerializer serializer = null, bool omitStandardNamespaces = false)
XmlSerializerNamespaces ns = null;
if (omitStandardNamespaces)
ns = new XmlSerializerNamespaces();
using (var textWriter = new StringWriter())
var settings = new XmlWriterSettings() { Indent = true };
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
(serializer ?? new XmlSerializer(obj.GetType())).Serialize(xmlWriter, obj, ns);
return textWriter.ToString();
public static string GetOuterXml(this XmlNode node, bool indent = true)
using (var textWriter = new StringWriter())
var settings = new XmlWriterSettings
OmitXmlDeclaration = true,
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
return textWriter.ToString();
public static class XmlAssert
public static void AreEqual(
Assert.IsTrue(XNode.DeepEquals(Normalize(expected), Normalize(actual)));
private static XElement Normalize(XElement element)
.OrderBy(a => a.Name.ToString()),
.OrderBy(a => a.Name.ToString())
.Select(e => Normalize(e)));
.OrderBy(a => a.Name.ToString()));
return new XElement(element.Name, element.Attributes()
.OrderBy(a => a.Name.ToString()), element.Value);
public static void Main()
Console.WriteLine("Roslyn 2.0 Compiler; Environment version: " + Environment.Version);
Console.WriteLine("Uncaught exception: ");