Color Of Code

Font Size

SCREEN

Profile

Layout

Menu Style

Cpanel

XML Serialization

User Rating:  / 1
PoorBest 

Assembly (reference)

System.Xml

Using directive

using System.Xml.Serialization;

Code: Creation of the serializer

The following code generates a serialization assembly on the fly (on first execution). This assembly is then used to read and write objects of the specified type.

XmlSerializer s = new XmlSerializer( typeof( MyType ) );

Code: Serialization

using (TextWriter writer = new StreamWriter( "data.xml" )) {
   s.Serialize( writer, myObject );
}

With settings

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
...
using (XmlWriter writer = new XmlWriter( "data.xml", settings )) {
   s.Serialize( writer, myObject );
}

Code: Deserialization

using (TextReader reader = new StreamReader( "data.xml" )) {
    myObject = (MyType)s.Deserialize( reader );
}

Omit namespace declarations

How to avoid the sometimes unwanted namespace declarations (xmlns:xsi, xmlns:xsd)

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
using (XmlWriter writer = new XmlWriter( "data.xml" )) {
   s.Serialize( writer, myObject, ns );
}

Useful method for XML streaming/filtering

This methods makes one step in copying the content from the reader to the writer. This makes writing of code to filter contents or inject nodes into XML easier.

static void WriteShallowNode (XmlReader reader, XmlWriter writer)
{
    switch (reader.NodeType) {
    case XmlNodeType.Element:
        writer.WriteStartElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
        writer.WriteAttributes (reader, true);
        if (reader.IsEmptyElement) {
            writer.WriteEndElement ();
        }
        break;
    case XmlNodeType.Text:
        writer.WriteString (reader.Value);
        break;
    case XmlNodeType.Whitespace:
    case XmlNodeType.SignificantWhitespace:
        writer.WriteWhitespace (reader.Value);
        break;
    case XmlNodeType.CDATA:
        writer.WriteCData (reader.Value);
        break;
    case XmlNodeType.EntityReference:
        writer.WriteEntityRef (reader.Name);
        break;
    case XmlNodeType.XmlDeclaration:
    case XmlNodeType.ProcessingInstruction:
        writer.WriteProcessingInstruction (reader.Name, reader.Value);
        break;
    case XmlNodeType.DocumentType:
        writer.WriteDocType (reader.Name, reader.GetAttribute ("PUBLIC"), reader.GetAttribute ("SYSTEM"), reader.Value);
        break;
    case XmlNodeType.Comment:
        writer.WriteComment (reader.Value);
        break;
    case XmlNodeType.EndElement:
        writer.WriteFullEndElement ();
        break;
    }
}

 

Add comment


Security code
Refresh

You are here: Home Code Snippets C# XML Serialization