ShouldSerialize*() vs *Specified Conditional Serialization Pattern

The intent of the {propertyName}Specified pattern is documented in XML Schema Binding Support: MinOccurs Attribute Binding Support. It was added to support an XSD schema element in which: The <element> element is involved. minOccurs is zero. The maxOccurs attribute dictates a single instance. The data type converts to a value type. In this case, xsd.exe … Read more

What is the best way to parse (big) XML in C# Code?

Use XmlReader to parse large XML documents. XmlReader provides fast, forward-only, non-cached access to XML data. (Forward-only means you can read the XML file from beginning to end but cannot move backwards in the file.) XmlReader uses small amounts of memory, and is equivalent to using a simple SAX reader. using (XmlReader myReader = XmlReader.Create(@”c:\data\coords.xml”)) … Read more

XML Serialization and namespace prefixes

To control the namespace alias, use XmlSerializerNamespaces. [XmlRoot(“Node”, Namespace=”http://flibble”)] public class MyType { [XmlElement(“childNode”)] public string Value { get; set; } } static class Program { static void Main() { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add(“myNamespace”, “http://flibble”); XmlSerializer xser = new XmlSerializer(typeof(MyType)); xser.Serialize(Console.Out, new MyType(), ns); } } If you need to change the namespace … Read more

Is it possible to deserialize XML into List?

You can encapsulate the list trivially: using System; using System.Collections.Generic; using System.Xml.Serialization; [XmlRoot(“user_list”)] public class UserList { public UserList() {Items = new List<User>();} [XmlElement(“user”)] public List<User> Items {get;set;} } public class User { [XmlElement(“id”)] public Int32 Id { get; set; } [XmlElement(“name”)] public String Name { get; set; } } static class Program { static … Read more

How do you serialize a string as CDATA using XmlSerializer?

[Serializable] public class MyClass { public MyClass() { } [XmlIgnore] public string MyString { get; set; } [XmlElement(“MyString”)] public System.Xml.XmlCDataSection MyStringCDATA { get { return new System.Xml.XmlDocument().CreateCDataSection(MyString); } set { MyString = value.Value; } } } Usage: MyClass mc = new MyClass(); mc.MyString = “<test>Hello World</test>”; XmlSerializer serializer = new XmlSerializer(typeof(MyClass)); StringWriter writer = new … Read more

Convert XML String to Object

You need to use the xsd.exe tool which gets installed with the Windows SDK into a directory something similar to: C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin And on 64-bit computers: C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\bin And on Windows 10 computers: C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin On the first run, you use xsd.exe and you convert your sample XML into a … Read more