Tag Archive: xml

ToXmlString extension method

This is an extension method that serializes any object to xml. Note that it is “null resistant” in that if the target is null, the extension does not throw an object-not-set-to-an-instance exception, but instead simply returns null.

public static string ToXmlString(this T item) where T : class
            if (item == null)
                return null;
            string xml;
            using (var stream = new MemoryStream())
            using (var writer = XmlWriter.Create(stream))
                new XmlSerializer(item.GetType()).Serialize(writer, item);
                xml = Encoding.UTF8.GetString(stream.ToArray());
            return xml;

Visual Studio Tip: Auto-format ASPX/ASP/HTML markup pages

If you have a messy markup page (ASPX, ASP, HTML, XML, etc.) that’s hard to read, just hit Ctrl-K then Ctrl-D and Visual Studio will instantly format it with carriage returns, nested tabs, etc.

For example, this:

<?xml version="1.0" encoding="utf-8" ?><myclass><myfield1><myfield2></myField2></myField1></myClass>

Becomes this:

<?xml version="1.0" encoding="utf-8" ?>
© 2018 Robert Corvus