none
Effective way of handling XML Serialization

    Question

  • I've used Xsd2Code to generate the Class and the subsequent Methods for Serialize and Deserialize.

    The following is the XSD which was used:

    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema id="BehCons" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="BehCons">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="Con" minOccurs="0" maxOccurs="unbounded">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="Val" type="xs:string"/>
                  <xs:element name="ValByCxt" nillable="true" minOccurs="0" maxOccurs="unbounded">
                    <xs:complexType>
                      <xs:simpleContent>
                        <xs:extension base="xs:string">
                          <xs:attribute name="Cl" type="xs:string" use="required"/>
                          <xs:attribute name="Cu" type="xs:string" use="required"/>
                          <xs:attribute name="Ch" type="xs:string" use="required"/>
                        </xs:extension>
                      </xs:simpleContent>
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
                <xs:attribute name="Name" type="xs:string" use="required"/>
                <xs:attribute name="Type" type="xs:string" use="required"/>
              </xs:complexType>
              <xs:unique name="ContextMustBeUnique">
                <xs:selector xpath="ValByCxt"/>
                <xs:field xpath="@Cl"/>
                <xs:field xpath="@Cu"/>
                <xs:field xpath="@Ch"/>
              </xs:unique>
            </xs:element>
            <xs:element name="Req">
              <xs:complexType>
                <xs:attribute name="Name" type="xs:string" />
              </xs:complexType>
            </xs:element>
            <xs:element name="Res">
              <xs:complexType>
                <xs:attribute name="Name" type="xs:string" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
        <xs:unique name="VariableMustBeUnique">
          <xs:selector xpath="Con"/>
          <xs:field xpath="@Name"/>
        </xs:unique>
      </xs:element>
    </xs:schema>


    Code Generated by using Xsd2Code for above XSD is:

    namespace XSD2XML
    {
        using System;
        using System.Diagnostics;
        using System.Xml.Serialization;
        using System.Collections;
        using System.Xml.Schema;
        using System.ComponentModel;
        using System.IO;
        using System.Text;
        using System.Collections.Generic;
        [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.1")]
        [System.SerializableAttribute()]
        [System.ComponentModel.DesignerCategoryAttribute("code")]
        [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
        [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
        public partial class BehCons
        {
            private List<BehConsCon> conField;
            private BehConsReq reqField;
            private BehConsRes resField;
            private static System.Xml.Serialization.XmlSerializer serializer;
            public BehCons()
            {
                this.resField = new BehConsRes();
                this.reqField = new BehConsReq();
                this.conField = new List<BehConsCon>();
            }
            [System.Xml.Serialization.XmlElementAttribute("Con", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
            public List<BehConsCon> Con
            {
                get
                {
                    return this.conField;
                }
                set
                {
                    this.conField = value;
                }
            }
            [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 1)]
            public BehConsReq Req
            {
                get
                {
                    return this.reqField;
                }
                set
                {
                    this.reqField = value;
                }
            }
            [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 2)]
            public BehConsRes Res
            {
                get
                {
                    return this.resField;
                }
                set
                {
                    this.resField = value;
                }
            }
            private static System.Xml.Serialization.XmlSerializer Serializer
            {
                get
                {
                    if ((serializer == null))
                    {
                        serializer = new System.Xml.Serialization.XmlSerializer(typeof(BehCons));
                    }
                    return serializer;
                }
            }
            #region Serialize/Deserialize
            /// <summary>
            /// Serializes current BehCons object into an XML document
            /// </summary>
            /// <returns>string XML value</returns>
            public virtual string Serialize()
            {
                System.IO.StreamReader streamReader = null;
                System.IO.MemoryStream memoryStream = null;
                try
                {
                    memoryStream = new System.IO.MemoryStream();
                    Serializer.Serialize(memoryStream, this);
                    memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                    streamReader = new System.IO.StreamReader(memoryStream);
                    return streamReader.ReadToEnd();
                }
                finally
                {
                    if ((streamReader != null))
                    {
                        streamReader.Dispose();
                    }
                    if ((memoryStream != null))
                    {
                        memoryStream.Dispose();
                    }
                }
            }
            /// <summary>
            /// Deserializes workflow markup into an BehCons object
            /// </summary>
            /// <param name="xml">string workflow markup to deserialize</param>
            /// <param name="obj">Output BehCons object</param>
            /// <param name="exception">output Exception value if deserialize failed</param>
            /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
            public static bool Deserialize(string xml, out BehCons obj, out System.Exception exception)
            {
                exception = null;
                obj = default(BehCons);
                try
                {
                    obj = Deserialize(xml);
                    return true;
                }
                catch (System.Exception ex)
                {
                    exception = ex;
                    return false;
                }
            }
            public static bool Deserialize(string xml, out BehCons obj)
            {
                System.Exception exception = null;
                return Deserialize(xml, out obj, out exception);
            }
            public static BehCons Deserialize(string xml)
            {
                System.IO.StringReader stringReader = null;
                try
                {
                    stringReader = new System.IO.StringReader(xml);
                    return ((BehCons)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
                }
                finally
                {
                    if ((stringReader != null))
                    {
                        stringReader.Dispose();
                    }
                }
            }
            #endregion
        }
        [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.1")]
        [System.SerializableAttribute()]
        [System.ComponentModel.DesignerCategoryAttribute("code")]
        [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
        public partial class BehConsCon
        {
            private string valField;
            private List<BehConsConValByCxt> valByCxtField;
            private string nameField;
            private string typeField;
            private static System.Xml.Serialization.XmlSerializer serializer;
            public BehConsCon()
            {
                this.valByCxtField = new List<BehConsConValByCxt>();
            }
            [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
            public string Val
            {
                get
                {
                    return this.valField;
                }
                set
                {
                    this.valField = value;
                }
            }
            [System.Xml.Serialization.XmlElementAttribute("ValByCxt", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable = true, Order = 1)]
            public List<BehConsConValByCxt> ValByCxt
            {
                get
                {
                    return this.valByCxtField;
                }
                set
                {
                    this.valByCxtField = value;
                }
            }
            [System.Xml.Serialization.XmlAttributeAttribute()]
            public string Name
            {
                get
                {
                    return this.nameField;
                }
                set
                {
                    this.nameField = value;
                }
            }
            [System.Xml.Serialization.XmlAttributeAttribute()]
            public string Type
            {
                get
                {
                    return this.typeField;
                }
                set
                {
                    this.typeField = value;
                }
            }
            private static System.Xml.Serialization.XmlSerializer Serializer
            {
                get
                {
                    if ((serializer == null))
                    {
                        serializer = new System.Xml.Serialization.XmlSerializer(typeof(BehConsCon));
                    }
                    return serializer;
                }
            }
            #region Serialize/Deserialize
            /// <summary>
            /// Serializes current BehConsCon object into an XML document
            /// </summary>
            /// <returns>string XML value</returns>
            public virtual string Serialize()
            {
                System.IO.StreamReader streamReader = null;
                System.IO.MemoryStream memoryStream = null;
                try
                {
                    memoryStream = new System.IO.MemoryStream();
                    Serializer.Serialize(memoryStream, this);
                    memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                    streamReader = new System.IO.StreamReader(memoryStream);
                    return streamReader.ReadToEnd();
                }
                finally
                {
                    if ((streamReader != null))
                    {
                        streamReader.Dispose();
                    }
                    if ((memoryStream != null))
                    {
                        memoryStream.Dispose();
                    }
                }
            }
            /// <summary>
            /// Deserializes workflow markup into an BehConsCon object
            /// </summary>
            /// <param name="xml">string workflow markup to deserialize</param>
            /// <param name="obj">Output BehConsCon object</param>
            /// <param name="exception">output Exception value if deserialize failed</param>
            /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
            public static bool Deserialize(string xml, out BehConsCon obj, out System.Exception exception)
            {
                exception = null;
                obj = default(BehConsCon);
                try
                {
                    obj = Deserialize(xml);
                    return true;
                }
                catch (System.Exception ex)
                {
                    exception = ex;
                    return false;
                }
            }
            public static bool Deserialize(string xml, out BehConsCon obj)
            {
                System.Exception exception = null;
                return Deserialize(xml, out obj, out exception);
            }
            public static BehConsCon Deserialize(string xml)
            {
                System.IO.StringReader stringReader = null;
                try
                {
                    stringReader = new System.IO.StringReader(xml);
                    return ((BehConsCon)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
                }
                finally
                {
                    if ((stringReader != null))
                    {
                        stringReader.Dispose();
                    }
                }
            }
            #endregion
        }
        [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.1")]
        [System.SerializableAttribute()]
        [System.ComponentModel.DesignerCategoryAttribute("code")]
        [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
        public partial class BehConsConValByCxt
        {
            private string clField;
            private string cuField;
            private string chField;
            private string valueField;
            private static System.Xml.Serialization.XmlSerializer serializer;
            [System.Xml.Serialization.XmlAttributeAttribute()]
            public string Cl
            {
                get
                {
                    return this.clField;
                }
                set
                {
                    this.clField = value;
                }
            }
            [System.Xml.Serialization.XmlAttributeAttribute()]
            public string Cu
            {
                get
                {
                    return this.cuField;
                }
                set
                {
                    this.cuField = value;
                }
            }
            [System.Xml.Serialization.XmlAttributeAttribute()]
            public string Ch
            {
                get
                {
                    return this.chField;
                }
                set
                {
                    this.chField = value;
                }
            }
            [System.Xml.Serialization.XmlTextAttribute()]
            public string Value
            {
                get
                {
                    return this.valueField;
                }
                set
                {
                    this.valueField = value;
                }
            }
            private static System.Xml.Serialization.XmlSerializer Serializer
            {
                get
                {
                    if ((serializer == null))
                    {
                        serializer = new System.Xml.Serialization.XmlSerializer(typeof(BehConsConValByCxt));
                    }
                    return serializer;
                }
            }
            #region Serialize/Deserialize
            /// <summary>
            /// Serializes current BehConsConValByCxt object into an XML document
            /// </summary>
            /// <returns>string XML value</returns>
            public virtual string Serialize()
            {
                System.IO.StreamReader streamReader = null;
                System.IO.MemoryStream memoryStream = null;
                try
                {
                    memoryStream = new System.IO.MemoryStream();
                    Serializer.Serialize(memoryStream, this);
                    memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                    streamReader = new System.IO.StreamReader(memoryStream);
                    return streamReader.ReadToEnd();
                }
                finally
                {
                    if ((streamReader != null))
                    {
                        streamReader.Dispose();
                    }
                    if ((memoryStream != null))
                    {
                        memoryStream.Dispose();
                    }
                }
            }
            /// <summary>
            /// Deserializes workflow markup into an BehConsConValByCxt object
            /// </summary>
            /// <param name="xml">string workflow markup to deserialize</param>
            /// <param name="obj">Output BehConsConValByCxt object</param>
            /// <param name="exception">output Exception value if deserialize failed</param>
            /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
            public static bool Deserialize(string xml, out BehConsConValByCxt obj, out System.Exception exception)
            {
                exception = null;
                obj = default(BehConsConValByCxt);
                try
                {
                    obj = Deserialize(xml);
                    return true;
                }
                catch (System.Exception ex)
                {
                    exception = ex;
                    return false;
                }
            }
            public static bool Deserialize(string xml, out BehConsConValByCxt obj)
            {
                System.Exception exception = null;
                return Deserialize(xml, out obj, out exception);
            }
            public static BehConsConValByCxt Deserialize(string xml)
            {
                System.IO.StringReader stringReader = null;
                try
                {
                    stringReader = new System.IO.StringReader(xml);
                    return ((BehConsConValByCxt)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
                }
                finally
                {
                    if ((stringReader != null))
                    {
                        stringReader.Dispose();
                    }
                }
            }
            #endregion
        }
        [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.1")]
        [System.SerializableAttribute()]
        [System.ComponentModel.DesignerCategoryAttribute("code")]
        [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
        public partial class BehConsReq
        {
            private string nameField;
            private static System.Xml.Serialization.XmlSerializer serializer;
            [System.Xml.Serialization.XmlAttributeAttribute()]
            public string Name
            {
                get
                {
                    return this.nameField;
                }
                set
                {
                    this.nameField = value;
                }
            }
            private static System.Xml.Serialization.XmlSerializer Serializer
            {
                get
                {
                    if ((serializer == null))
                    {
                        serializer = new System.Xml.Serialization.XmlSerializer(typeof(BehConsReq));
                    }
                    return serializer;
                }
            }
            #region Serialize/Deserialize
            /// <summary>
            /// Serializes current BehConsReq object into an XML document
            /// </summary>
            /// <returns>string XML value</returns>
            public virtual string Serialize()
            {
                System.IO.StreamReader streamReader = null;
                System.IO.MemoryStream memoryStream = null;
                try
                {
                    memoryStream = new System.IO.MemoryStream();
                    Serializer.Serialize(memoryStream, this);
                    memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                    streamReader = new System.IO.StreamReader(memoryStream);
                    return streamReader.ReadToEnd();
                }
                finally
                {
                    if ((streamReader != null))
                    {
                        streamReader.Dispose();
                    }
                    if ((memoryStream != null))
                    {
                        memoryStream.Dispose();
                    }
                }
            }
            /// <summary>
            /// Deserializes workflow markup into an BehConsReq object
            /// </summary>
            /// <param name="xml">string workflow markup to deserialize</param>
            /// <param name="obj">Output BehConsReq object</param>
            /// <param name="exception">output Exception value if deserialize failed</param>
            /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
            public static bool Deserialize(string xml, out BehConsReq obj, out System.Exception exception)
            {
                exception = null;
                obj = default(BehConsReq);
                try
                {
                    obj = Deserialize(xml);
                    return true;
                }
                catch (System.Exception ex)
                {
                    exception = ex;
                    return false;
                }
            }
            public static bool Deserialize(string xml, out BehConsReq obj)
            {
                System.Exception exception = null;
                return Deserialize(xml, out obj, out exception);
            }
            public static BehConsReq Deserialize(string xml)
            {
                System.IO.StringReader stringReader = null;
                try
                {
                    stringReader = new System.IO.StringReader(xml);
                    return ((BehConsReq)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
                }
                finally
                {
                    if ((stringReader != null))
                    {
                        stringReader.Dispose();
                    }
                }
            }
            #endregion
        }
        [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.1")]
        [System.SerializableAttribute()]
        [System.ComponentModel.DesignerCategoryAttribute("code")]
        [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
        public partial class BehConsRes
        {
            private string nameField;
            private static System.Xml.Serialization.XmlSerializer serializer;
            [System.Xml.Serialization.XmlAttributeAttribute()]
            public string Name
            {
                get
                {
                    return this.nameField;
                }
                set
                {
                    this.nameField = value;
                }
            }
            private static System.Xml.Serialization.XmlSerializer Serializer
            {
                get
                {
                    if ((serializer == null))
                    {
                        serializer = new System.Xml.Serialization.XmlSerializer(typeof(BehConsRes));
                    }
                    return serializer;
                }
            }
            #region Serialize/Deserialize
            /// <summary>
            /// Serializes current BehConsRes object into an XML document
            /// </summary>
            /// <returns>string XML value</returns>
            public virtual string Serialize()
            {
                System.IO.StreamReader streamReader = null;
                System.IO.MemoryStream memoryStream = null;
                try
                {
                    memoryStream = new System.IO.MemoryStream();
                    Serializer.Serialize(memoryStream, this);
                    memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                    streamReader = new System.IO.StreamReader(memoryStream);
                    return streamReader.ReadToEnd();
                }
                finally
                {
                    if ((streamReader != null))
                    {
                        streamReader.Dispose();
                    }
                    if ((memoryStream != null))
                    {
                        memoryStream.Dispose();
                    }
                }
            }
            /// <summary>
            /// Deserializes workflow markup into an BehConsRes object
            /// </summary>
            /// <param name="xml">string workflow markup to deserialize</param>
            /// <param name="obj">Output BehConsRes object</param>
            /// <param name="exception">output Exception value if deserialize failed</param>
            /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
            public static bool Deserialize(string xml, out BehConsRes obj, out System.Exception exception)
            {
                exception = null;
                obj = default(BehConsRes);
                try
                {
                    obj = Deserialize(xml);
                    return true;
                }
                catch (System.Exception ex)
                {
                    exception = ex;
                    return false;
                }
            }
            public static bool Deserialize(string xml, out BehConsRes obj)
            {
                System.Exception exception = null;
                return Deserialize(xml, out obj, out exception);
            }
            public static BehConsRes Deserialize(string xml)
            {
                System.IO.StringReader stringReader = null;
                try
                {
                    stringReader = new System.IO.StringReader(xml);
                    return ((BehConsRes)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
                }
                finally
                {
                    if ((stringReader != null))
                    {
                        stringReader.Dispose();
                    }
                }
            }
            #endregion
        }
    }

    I've the following result set from DB:

    DB resultset in text format (Check this data in 'Lucida Console' font in Regular '10' size)

    Type  Name  Val  Cl  Cu  Ch  Req  Res
    -------------- -------------- -------------- -------------- -------------- -------------- -------------- --------------
    Str  Key  value  NULL  NULL  NULL  
    Bool  Active  MainValue NULL  NULL  NULL  
    Bool  Active  newval  sur  en-US  WEB  
    Bool  Active  anoval  sur  en-US  WEB  
    Bool  Active  val  cl  cu  ch  
                Res.sur.ear Req.sur.ear

    And I want the output XML in the following format for the above DB Resultset :

    <?xml version="1.0" encoding="utf-8"?> <Cons> <Con Type="Str" Name="Key"> <Value>Value1</Value> </Con> <Con Type="Bool" Name="Active"> <Value>MainValue</Value> </Con> <Con> <ValByCxt Cl="sur" Cu="en-US" Ch="WEB">newval</ValByCxt> </Con> <Con> <ValByCxt Cl="sur" Cu="en-US" Ch="WEB">anoval</ValByCxt> </Con> <Con> <ValByCxt Cl="cl" Cu="cu" Ch="ch">val</ValByCxt> </Con> <Req Name="Res.sur.ear" /> <Res Name="Req.sur.ear" /> </Cons>

     


    Now, I've the following code which creates the above described XML as per the XSD.

    protected void btnGenerateNewXML_Click(object sender, EventArgs e)
            {
                try
                {
                    string previousType = string.Empty;
                    string previousName = string.Empty;
                    System.Data.DataSet ds = GetBehaviorConfig();
                    var data = new NewConfiguration.BehCons();
                    if (ds.Tables.Count > 0)
                    {
                        foreach (System.Data.DataTable dt in ds.Tables)
                        {
                            foreach (System.Data.DataRow dr in dt.Rows)
                            {
                                if (!string.IsNullOrEmpty(dr[0].ToString()))
                                {   
                                    if (previousType != dr[0].ToString() && previousName != dr[1].ToString())
                                    {
                                        previousType = dr[0].ToString();
                                        previousName = dr[1].ToString();
                                        data.Con.Add(new NewConfiguration.BehConsCon
                                        {
                                            Type = dr[0].ToString(),
                                            Name = dr[1].ToString(),
                                            Val = dr[2].ToString()
                                        });
                                    }
                                }
                                if (!string.IsNullOrEmpty(dr[3].ToString()))
                                {//abc
                                    var vbc = new NewConfiguration.BehConsCon();
                                    vbc.ValByCxt.Add(new NewConfiguration.BehConsConValByCxt
                                    {
                                        Cl = dr[3].ToString(),
                                        Cu = dr[4].ToString(),
                                        Ch = dr[5].ToString(),
                                        Value = dr[2].ToString()
                                    });
                                    data.Con.Add((NewConfiguration.BehConsCon)vbc);\\xyz
                                }
                                data.Req.Name = dr[6].ToString();
                                data.Res.Name = dr[7].ToString();
                            }
                        }
                    }
                    var serializer = new System.Xml.Serialization.XmlSerializer(typeof(NewConfiguration.BehCons));
                    using (var stream = new System.IO.StreamWriter("C:\\behcfg.xml"))
                        serializer.Serialize(stream, data);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }

    I've the following queries

    1. I need to generate the above XML exactly the way it is. But the code above has issues which I add the 'vbc' object. It creates multiple <Cons> object and this is not as per my requirement. - Issue where I've commented \\abc till \\xyz in the above code

    2. Is the above code the most effective method, or there can be a better code with lesser validation to achieve the same result?


    • Edited by SATISD9X Wednesday, April 10, 2013 8:57 AM
    Wednesday, April 10, 2013 8:14 AM

All replies

  • I've doubt on a part of XSD.

    <xs:element name="ValByCxt" nillable="true" minOccurs="0" maxOccurs="unbounded">
                    <xs:complexType>
                      <xs:simpleContent>
                        <xs:extension base="xs:string">
                          <xs:attribute name="Cl" type="xs:string" use="required"/>
                          <xs:attribute name="Cu" type="xs:string" use="required"/>
                          <xs:attribute name="Ch" type="xs:string" use="required"/>
                        </xs:extension>
                      </xs:simpleContent>
                    </xs:complexType>
                  </xs:element>

    instead of above part, it can be like the following, it's just my guess.

    <xs:element name="ValByCxt" nillable="true" minOccurs="0" maxOccurs="unbounded">
                    <xs:simpleType>
                        <xs:extension base="xs:string">
                          <xs:attribute name="Cl" type="xs:string" use="required"/>
                          <xs:attribute name="Cu" type="xs:string" use="required"/>
                          <xs:attribute name="Ch" type="xs:string" use="required"/>
                        </xs:extension>
                      </xs:simpleType>
                  </xs:element>


    Faisal Ahmed Farooqui

    Thursday, April 25, 2013 3:21 PM