Posts

Showing posts with the label XML

C# parse invalid XML characters

I've been dealing with XML a bit lately and have found that when you don't control the data you get all sorts of weird stuff. XML 1.0 doesn't allow certain characters or the XML is invalid. I tested a variety of ways using streams and string builders but I found a bit of LINQ and using a .NET function and in two lines you get a string of XML that only has valid characters. var validXmlChars = val.Where( ch => XmlConvert.IsXmlChar( ch ) ).ToArray(); return new string( validXmlChars );

C# Serialize an object to/from XML

There have been many times I've needed to serialize an object to/from XML. .NET makes this incredibly easy. With a few meta tags your class(es) can easily be serialized and deserialized. You can then take this even further any start applying custom attributes to have as much granular control over the serialization as you want. For instance lets' take a very basic class with some data and properties. public class Person { int _age; String _name; /// Gets or sets the Age of the person. public int Age { get { return _age; } set { _age = value; } } /// Gets or sets the Name of the person. public String Name { get { return _name; } set { _name = value; } } /// Creates a new instance of the Person class public Person() { } } Now let's take this class and add the [Serializable] attribute. [Serializable] public class Person { int _age; String _name; /// Gets or sets the Age...