Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read From XML File into C# Class Using Serialization

Tags:

c#

xml

I have the following XML file that i am trying to read into a class in c# using DE-serialization:

<?xml version="1.0"?>
    <PropertiesMapping>
        <Property>
            <WEB_Class>InfoRequest</WEB_Class>
            <COM_Class>CInfoReq</COM_Class>
            <Mappings>
                <Map>
                    <WEB_Property>theId</WEB_Property>
                    <COM_Property>TheID</COM_Property>
                </Map>
                <Map>
                    <WEB_Property>theName</WEB_Property>
                    <COM_Property>NewName</COM_Property>
                </Map>
            </Mappings>
        </Property>
    </PropertiesMapping>

The following is the code I am using, and while it executes without error no data gets read into the class PropertiesMapping, where am i going wrong??

PropertiesMapping pm = null;

        try
        {
            System.IO.StreamReader str = new System.IO.StreamReader(@"PropertyMapping.xml");
            System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(typeof(PropertiesMapping));
            pm = (PropertiesMapping)xSerializer.Deserialize(str);
            str.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }


[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public class PropertiesMapping
    {
        private string m_WEB_Class = "";
        private string m_COM_Class = "";

        private List<IndividualProperties> m_EachProperty = null;

        public string WEB_Class
        {
            get
            {
                return m_WEB_Class;
            }
            set
            {
                m_WEB_Class = value;
            }
        }

        public string COM_Class
        {
            get
            {
                return m_COM_Class;
            }
            set
            {
                m_COM_Class = value;
            }
        }

        public IndividualProperties GetIndividualProperties(int iIndex)
        {
            return m_EachProperty[iIndex];
        }

        public void SetIndividualProperties(IndividualProperties theProp)
        {
            m_EachProperty.Add(theProp);
        }
    }



public class IndividualProperties
    {
        private string m_WEB_PropertyField;

        private string m_COM_PropertyField;

        public string WEB_Property
        {
            get
            {
                return this.m_WEB_PropertyField;
            }
            set
            {
                this.m_WEB_PropertyField = value;
            }
        }

        public string COM_Property
        {
            get
            {
                return this.m_COM_PropertyField;
            }
            set
            {
                this.m_COM_PropertyField = value;
            }
        }
    }
like image 866
KF-SoftwareDev Avatar asked Aug 20 '13 16:08

KF-SoftwareDev


People also ask

What is XML parser in C?

The Oracle XML parser for C reads an XML document and uses DOM or SAX APIs to provide programmatic access to its content and structure. You can use the parser in validating or nonvalidating mode. This chapter assumes that you are familiar with the following technologies: Document Object Model (DOM).

How do I read XML files?

XML files are encoded in plaintext, so you can open them in any text editor and be able to clearly read it. Right-click the XML file and select "Open With." This will display a list of programs to open the file in. Select "Notepad" (Windows) or "TextEdit" (Mac).

What is C in XML?

The C$XML routine is useful for parsing all XML files, including non-records-based XML files such as XFDs or configuration files that you have formatted in XML.


2 Answers

You don't need to explicitly declare the properties. Just make sure the names match. The only non-default portion is the [XmlArrayItem("Map")] attribute you will need to use the different name for the map array.

You can, however, use differing names as I have for the COM_Property and WEB_Property by specifying the XmlElementAttribute.

class Program
{
    static void Main(string[] args)
    {
        string testData = @"<?xml version=""1.0""?>
<PropertiesMapping>
    <Property>
        <WEB_Class>InfoRequest</WEB_Class>
        <COM_Class>CInfoReq</COM_Class>
        <Mappings>
            <Map>
                <WEB_Property>theId</WEB_Property>
                <COM_Property>TheID</COM_Property>
            </Map>
            <Map>
                <WEB_Property>theName</WEB_Property>
                <COM_Property>NewName</COM_Property>
            </Map>
        </Mappings>
    </Property>
</PropertiesMapping>";

        var sr = new System.IO.StringReader(testData);
        var xs = new XmlSerializer(typeof(PropertiesMapping));

        object result = xs.Deserialize(sr);
    }
}

[Serializable]
public class PropertiesMapping
{
    public Property Property { get; set; }
}

[Serializable]
public class Property
{
    [XmlElement("WEB_Class")]
    public string WebClass { get; set; }

    [XmlElement("COM_Class")]
    public string ComClass { get; set; }

    [XmlArrayItem("Map")]
    public Mapping[] Mappings { get; set; }
}

[Serializable]
public class Mapping
{
    [XmlElement("WEB_Property")]
    public string WebProperty { get; set; }

    [XmlElement("COM_Property")]
    public string ComProperty { get; set; }
}
like image 112
Mitch Avatar answered Oct 17 '22 09:10

Mitch


You can use the XmlElementAttribute to simplify your C# naming.

Indicates that a public field or property represents an XML element when the XmlSerializer serializes or deserializes the object that contains it.

You will need to use XmlArrayItemAttribute for the Mappings element.

Represents an attribute that specifies the derived types that the XmlSerializer can place in a serialized array.

Classes:

[XmlType("PropertiesMapping")]
public class PropertyMapping
{
    public PropertyMapping()
    {
        Properties = new List<Property>();
    }

    [XmlElement("Property")]
    public List<Property> Properties { get; set; }
}

public class Property
{
    public Property()
    {
        Mappings = new List<Mapping>();
    }

    [XmlElement("WEB_Class")]
    public string WebClass { get; set; }

    [XmlElement("COM_Class")]
    public string ComClass { get; set; }

    [XmlArray("Mappings")]
    [XmlArrayItem("Map")]
    public List<Mapping> Mappings { get; set; }
}

[XmlType("Map")]
public class Mapping
{
    [XmlElement("WEB_Property")]
    public string WebProperty { get; set; }

    [XmlElement("COM_Property")]
    public string ComProperty { get; set; }
}

Demo:

PropertyMapping result;

var serializer = new XmlSerializer(typeof(PropertyMapping));

using(var stream = new StringReader(data))
using(var reader = XmlReader.Create(stream))
{
    result = (PropertyMapping) serializer.Deserialize(reader);
}
like image 23
Dustin Kingen Avatar answered Oct 17 '22 09:10

Dustin Kingen