using System.Collections.Generic;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;
[XmlRoot("Car", Namespace = "http://MyNamespace")]
[XmlType("Car", Namespace = "http://MyNamespace")]
public string make { get; set; }
public static void Test()
static string XmlContent = @"
<RootNode xmlns=""http://MyNamespace"">
<Car make=""Volkswagen"" />
static string XmlContent2 = @"
<RootNode xmlns:ns=""http://MyNamespace"">
<ns:Car make=""Volkswagen"" />
private static void TestWriteMcve()
TestWriteMcve(XmlContent);
TestWriteMcve(XmlContent2);
private static void TestWriteMcve(string content)
var doc = new XmlDocument();
var nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("myns", "http://MyNamespace");
var newCar = new Car { make = "BMW" };
var node = doc.DocumentElement.SelectSingleNode("myns:Cars/myns:Car[@make='Ford']", nsMgr);
node = TestReplace(doc, node, newCar);
node = TestReplace(doc, node, null);
node = TestReplace(doc, node, newCar);
private static XmlNode TestReplace(XmlDocument doc, XmlNode node, Car newCar)
node = node.ReplaceWithSerializationOf(newCar);
var parent = node.ParentNode;
Console.WriteLine("Replacement: ");
Console.WriteLine(node.OuterXml);
Console.WriteLine("Entire document: ");
Console.WriteLine(doc.GetOuterXml());
public static class XmlNodeExtensions
public static XmlNode ReplaceWithSerializationOf<T>(this XmlNode node, T replacement)
throw new ArgumentNullException();
var parent = node.ParentNode;
var serializer = new XmlSerializer(replacement == null ? typeof(T) : replacement.GetType());
using (var writer = node.CreateNavigator().InsertAfter())
writer.WriteWhitespace("");
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add(node.GetNamespaceOfPrefix(node.NamespaceURI), node.NamespaceURI);
serializer.Serialize(writer, replacement, ns);
var nextNode = node.NextSibling;
parent.RemoveChild(node);
public static class XmlSerializationHelper
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 class AssertionFailedException : System.Exception
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
public static class Assert
public static void IsTrue(bool value)
public static void IsTrue(bool value, string message)
throw new AssertionFailedException(message ?? "failed");
public static void Main()
Console.WriteLine("Roslyn 2.0 Compiler; Environment version: " + Environment.Version);
Console.WriteLine("Uncaught exception: ");