简体   繁体   中英

Set default value for attributes which are null while deserializing XML

I have a xml file which I am trying to deserialize. I am implementing IXmlSerializable interface for Serialization and Deserialization. I don't see any problem with the Serialization. But with the deserialization I have few problems. 1). I am using xml reader's 'ReadToFollowing' for reading elements. With this approach I have to read the values in the order of elements. If there is any mismatch in the order I am not able to read the remainig values. 2). As per my requirement I have to provide backward compatibility in deserializing the xml. Because of this when I load some of the old version xml files(which may not contain all the elements as the latest version xml), 'ReadToFollowing' throwing exceptions.

Latest version Xml

<LEFTSECTION>
        <DATA />
        <FONTNAME>Arial</FONTNAME>
        <FONTSTYLE>Regular</FONTSTYLE>
        <FONTSIZE>10</FONTSIZE>
        <TEXTCOLOR>-16777216</TEXTCOLOR>
        <STRIKEOUT>0</STRIKEOUT>
        <UNDERLINE>0</UNDERLINE>
        <BORDER>0</BORDER>
        <IMAGE>0</IMAGE>
        <IMAGENAME />
        <ALIGNMENT>4</ALIGNMENT>
        <SECTIONHEIGHT>0.5454546</SECTIONHEIGHT>
        <SECTIONWIDTH>0.33</SECTIONWIDTH>
      </LEFTSECTION>

Old version Xml

<LEFTSECTION>
        <DATA>asas#APP_OEM_NAME#</DATA>
        <FONTNAME>Arial Unicode MS</FONTNAME>
        <FONTSTYLE>Regular</FONTSTYLE>
        <FONTSIZE>10</FONTSIZE>
        <TEXTCOLOR>-16777216</TEXTCOLOR>
        <STRIKEOUT>0</STRIKEOUT>
        <UNDERLINE>0</UNDERLINE>
        <BORDER>0</BORDER>
        <IMAGE>0</IMAGE>
        <IMAGENAME>
        </IMAGENAME>
      </LEFTSECTION>

Please help me on this.

Okay. I've had a play and this is what I've come up with:

Serializeable class:

[Serializable]
[XmlRoot("LEFTSECTION")]
public class NewClass
{
    [XmlElement("DATA")]
    [System.ComponentModel.DefaultValueAttribute("")]
    public string Data;

    [XmlElement("FONTNAME")]
    public string FontName;

    [XmlElement("FONTSTYLE")]
    public string FontStyle;

    [XmlElement("FONTSIZE")]
    public int FontSize;

    [XmlElement("TEXTCOLOR")]
    public int TextColor;

    [XmlElement("STRIKEOUT")]
    public int Strikeout;

    [XmlElement("UNDERLINE")]
    public int Underline;

    [XmlElement("BORDER")]
    public int Border;

    [XmlElement("IMAGE")]
    public int Image;

    [XmlElement("IMAGENAME")]
    public string ImageName;

    [System.ComponentModel.DefaultValue(0)]
    [XmlElement("ALIGNMENT")]
    public int Alignment;

    [XmlElement("SECTIONHEIGHT")]
    public double SectionHeight;

    [XmlElement("SECTIONWIDTH")]
    public double SectionWidth;
}

Then code in my test program:

    NewClass test = new NewClass();
    XmlSerializer serializer = new XmlSerializer(typeof(NewClass));

    FileStream file = new FileStream("input.xml", FileMode.Open);
    test = (NewClass) serializer.Deserialize(file);
    file.Close();

    file = new FileStream("old.xml", FileMode.Open);
    test = (NewClass)serializer.Deserialize(file);
    file.Close();

Contents of input.xml:

<?xml version="1.0" encoding="utf-8" ?>
<LEFTSECTION>
  <DATA />
  <FONTNAME>Arial</FONTNAME>
  <FONTSTYLE>Regular</FONTSTYLE>
  <FONTSIZE>10</FONTSIZE>
  <TEXTCOLOR>-16777216</TEXTCOLOR>
  <STRIKEOUT>0</STRIKEOUT>
  <UNDERLINE>0</UNDERLINE>
  <BORDER>0</BORDER>
  <IMAGE>0</IMAGE>
  <IMAGENAME />
  <ALIGNMENT>4</ALIGNMENT>
  <SECTIONHEIGHT>0.5454546</SECTIONHEIGHT>
  <SECTIONWIDTH>0.33</SECTIONWIDTH>
</LEFTSECTION>

Contents of old.xml:

<LEFTSECTION>
  <DATA>asas#APP_OEM_NAME#</DATA>
  <FONTNAME>Arial Unicode MS</FONTNAME>
  <FONTSTYLE>Regular</FONTSTYLE>
  <FONTSIZE>10</FONTSIZE>
  <TEXTCOLOR>-16777216</TEXTCOLOR>
  <STRIKEOUT>0</STRIKEOUT>
  <UNDERLINE>0</UNDERLINE>
  <BORDER>0</BORDER>
  <IMAGE>0</IMAGE>
  <IMAGENAME>
  </IMAGENAME>
</LEFTSECTION>

This populates my class correctly. Notice that on Data and Alignment properties of my class I set default values if they don't exist. Also they're all renamed from what is in the file.

I hope that this helps.

edit

Ah I see, you're stuck with IXmlSerializable methods for your classes.

Try this it's not pretty but it appears to work:

Here's my IXMLSerializable class:

   public class XmlSerializableNewClass : IXmlSerializable
    {
        public string Data;
        public string FontName;
        public string FontStyle;
        public int FontSize;
        public int TextColor;
        public int Strikeout;
        public int Underline;
        public int Border;
        public int Image;
        public string ImageName;
        public int Alignment;
        public double SectionHeight;
        public double SectionWidth;
        public string[]elementNames={"DATA", "FONTNAME", "FONTSTYLE","FONTSIZE","TEXTCOLOR","STRIKEOUT", "UNDERLINE", "BORDER", "IMAGE", "IMAGENAME", "ALIGNMENT", "SECTIONHEIGHT", "SECTIONWIDTH"};

        #region IXmlSerializable Members

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            //set default values
            Data=string.Empty;
            FontName = string.Empty;
            FontStyle = string.Empty;
            FontSize = 0;
            TextColor = 0;
            Strikeout = 0;
            Underline = 0;
            Border = 0;
            Image = 0;
            ImageName = string.Empty;
            Alignment = 0;
            SectionHeight = 0.0;
            SectionWidth = 0.0;

            reader.MoveToContent();

            Boolean isEmptyElement= false;
            isEmptyElement = reader.IsEmptyElement;
            reader.ReadStartElement();
            for (int i=0; i< elementNames.Length; i++)
            {
                isEmptyElement = reader.IsEmptyElement;
                string s = reader.Name;
                switch (s)
                {
                    case "DATA":
                        if (!isEmptyElement)
                        {
                            Data = reader.ReadElementString("DATA");
                        }
                        else
                        {
                            Data = string.Empty;
                            reader.ReadStartElement();
                        }
                        break;
                    case "FONTNAME":
                        if (!isEmptyElement)
                        {
                            FontName = reader.ReadElementString("FONTNAME");
                        }
                        else
                        {
                            FontName = string.Empty;
                            reader.ReadStartElement();
                        }
                        break;
                    case "FONTSTYLE":
                        if (!isEmptyElement)
                        {
                            FontStyle = reader.ReadElementString("FONTSTYLE");
                        }
                        else
                        {
                            FontStyle = string.Empty;
                            reader.ReadStartElement();
                        }
                        break;
                    case "FONTSIZE":
                        if (!isEmptyElement)
                        {
                            FontSize = reader.ReadElementContentAsInt();
                        }
                        else
                        {
                            FontSize = 0;
                            reader.ReadEndElement();
                        }
                        break;
                    case "TEXTCOLOR":
                        if (!isEmptyElement)
                        {
                            TextColor = reader.ReadElementContentAsInt();
                        }
                        else
                        {
                            TextColor = 0;
                            reader.ReadStartElement();
                        }
                        break;
                    case "STRIKEOUT":
                        if (!isEmptyElement)
                        {
                            Strikeout = reader.ReadElementContentAsInt();
                        }
                        else
                        {
                            Strikeout = 0;
                            reader.ReadStartElement();
                        }
                        break;
                    case "UNDERLINE":
                        if (!isEmptyElement)
                        {
                            Underline = reader.ReadElementContentAsInt();
                        }
                        else
                        {
                            Underline = 0;
                            reader.ReadStartElement();
                        }
                        break;
                    case "BORDER":
                        if (!isEmptyElement)
                        {
                            Border = reader.ReadElementContentAsInt();
                        }
                        else
                        {
                            Border = 0;
                            reader.ReadStartElement();
                        }
                        break;
                    case "IMAGE":
                        if (!isEmptyElement)
                        {
                            Image = reader.ReadElementContentAsInt();
                        }
                        else
                        {
                            Image = 0;
                            reader.ReadStartElement();
                        }
                        break;
                    case "IMAGENAME":
                        if (!isEmptyElement)
                        {
                            ImageName = reader.ReadElementString("IMAGENAME");
                        }
                        else
                        {
                            ImageName = string.Empty;
                            reader.ReadStartElement();
                        }
                        break;
                    case "ALIGNMENT":
                        if (!isEmptyElement)
                        {
                            Alignment = reader.ReadElementContentAsInt();
                        }
                        else
                        {
                            Alignment = 0;
                            reader.ReadStartElement();
                        }
                        break;
                    case "SECTIONHEIGHT":
                        if (!isEmptyElement)
                        {
                            SectionHeight = reader.ReadElementContentAsDouble();
                        }
                        else
                        {
                            SectionHeight = 0;
                            reader.ReadStartElement();
                        }
                        break;
                    case "SECTIONWIDTH":
                        if (!isEmptyElement)
                        {
                            SectionWidth = reader.ReadElementContentAsDouble();
                        }
                        else
                        {
                            SectionWidth = 0;
                            reader.ReadEndElement();
                        }
                        break;
                }
            }
            reader.ReadEndElement();
       }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

I've gone a bit overboard with handling empty elements.

Here's the calling code, everything else is the same:

    XmlSerializableNewClass test2 = new XmlSerializableNewClass();

    System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
    settings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment;
    settings.IgnoreWhitespace = true;
    settings.IgnoreComments = true;
    System.Xml.XmlReader reader = System.Xml.XmlReader.Create("input.xml", settings);

    test2.ReadXml(reader);

    reader = System.Xml.XmlReader.Create("old.xml", settings);
    test2.ReadXml(reader);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM