Remove declaration and namespaces from XML serializer

Out of the box, .NET XML serialization is loaded with garbage that I personally never want. It’s one of the reasons I use JSON instead of XML whenever possible. But one quick way to remove the junk, assuming you’re dealing with simple data, and don’t care about things like encoding or namespaces or whatever, is […]

Fluent XML writer

Writing XML in .NET is not too terrible, but it sometimes is a bit tricky and lengthy. A few years ago, I put this library together to write XML easily, using fluent techniques. static void Main(string[] args) { FluentXmlWriter.Start(“root”) .Simple(“First”) .Simple(“Second”).Attr(“a”, “b”) .Complex(“Arr”) .ManySimple( SimpleElement.Create(“Arr1”).Attr(“key1”, “val1”), SimpleElement.Create(“Arr2”).Attr(“key2”, “val2”) ).EndElem() .Complex(“Third”).Text(“My Text”).EndElem() .Complex(“Fourth”).CData(“Hello there!”).EndElem() .Comment(“A comment!”) […]

SQL XML Nested Types

declare @people table (id int, name varchar(50));insert @people values (1, ‘John’);insert @people values (2, ‘Mary’);insert @people values (3, ‘Pat’);declare @cars table (id int, model varchar(50), person_id int);insert @cars values (1, ‘Corvette’, 1);insert @cars values (2, ‘Mustang’, 1);insert @cars values (3, ‘Viper’, 2);select p.id [@id] ,p.name [@name] ,( select model [@model] from @cars where person_id = […]

XML Serialization Helpers

public static class Serialization { private static readonly Encoding _defaultEncoding = Encoding.UTF8; public static T DeserializeXmlFile<T>(string fileName) { if (!File.Exists(fileName)) throw new FileNotFoundException(); var serializer = new XmlSerializer(typeof(T)); using (var xmlReader = new XmlTextReader(fileName)) { return (T)serializer.Deserialize(xmlReader); } } public static T Deserialize<T>(TextReader textReader) { if (textReader == null) throw new ArgumentNullException(“textReader”); var serializer = […]

.NET XML Writer

XmlWriter is an easy way to generate XML when you need it. If you’re building something more complex, like something for an API, you probably want to go with serialization instead. Otherwise, this is pretty easy to build XML how you want it top to bottom. View code on GitHub