XML serialization with namespace setting : Xml serialization « XML « C# / CSharp Tutorial






using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

class MainClass{

  public static void Main(){
     try {
         ShapedRoot sr = new ShapedRoot();
         sr.node = new Shaped();
         sr.node.s1 = "a value";
         sr.node.s2 = "another value";
         sr.node.s3 = "uuid:1AE0964A-2B30-4a02-96F2-325B92B4E92C";

         StringWriter sw = new StringWriter();
         XmlTextWriter tw = new XmlTextWriter( sw );
         tw.Formatting = Formatting.Indented;
         tw.Indentation = 4;

         XmlSerializer ser = new XmlSerializer( typeof( ShapedRoot ) );
         ser.Serialize( tw, sr );

         tw.Close();
         sw.Close();

     }
     catch( Exception exc )
     {
         Console.WriteLine( exc.Message );
     }
 
  }
}

[XmlRoot( ElementName="sroot", Namespace="urn:my-examples:shaping" )]
public class ShapedRoot
{
    public ShapedRoot()
    {
    }

    public Shaped node;
}

[XmlType( Namespace="urn:my-examples:shaping" )]
public class Shaped
{
    public Shaped()
    {
    }

    [XmlAttribute]
    public string s1;

    [XmlElement( ElementName = "string2" )]
    public string s2;

    [XmlElement( DataType = "anyURI" )]
    public string s3;
}








30.30.Xml serialization
30.30.1.XML serialization with namespace setting
30.30.2.Serialize/Deserialize Xml: deal with element list
30.30.3.Specify the XmlRoot and XmlAttribute for XML serialization
30.30.4.Specify format and indentation for object XML serialization
30.30.5.Using XmlSerializer to Serialize a Linq object
30.30.6.XML Serialization Sample
30.30.7.Serialization of an object marked with XmlAttribute and XmlIgnore
30.30.8.Serialize a list of object to Xml with Linq
30.30.9.Xml Serialization for Enum
30.30.10.Xml Serialization for DateTime value
30.30.11.Assign XmlArrayAttribute to two arrays, and serializes a class instance that contains those arrays.
30.30.12.XmlTextAttribute with type string informs the XmlSerializer that strings should be serialized as XML text