user2838148
user2838148

Reputation: 21

C# Deserialization xml file

I try to deserialize xml file:

<?xml version="1.0" encoding="utf-8"?>
<XmlFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <OBJECTS ITEM="ItemValue" TABLE_NAME="TableExample">
    </OBJECTS>
</XmlFile>

My deserialize class code looks like that:

[Serializable]
[XmlRoot("XmlFile")]
public class SerializeObject
{

    [XmlAttribute("ITEM")]
    public string Item { get; set; }

    [XmlAttribute("TABLE_NAME")]
    public string Table_Name { get; set; }
}

When I try deserialize xml file i always got no errors and Item and Table_Name equals null. Why?

Thx for replay

Upvotes: 2

Views: 5675

Answers (2)

Davidson Sousa
Davidson Sousa

Reputation: 1353

leaving here a more complete example in case anyone needs: http://davidsonsousa.net/en/post/serializedeserialize-objects-to-xml-with-c

Cheers!

Upvotes: 1

Benoit Blanchon
Benoit Blanchon

Reputation: 14571

[XmlRoot("XmlFile")]
public class SerializableContainer
{
    [XmlElement("OBJECTS")]
    public SerializeObject[] Objects { get; set; }
}

public class SerializeObject
{
    [XmlAttribute("ITEM")]
    public string Item { get; set; }

    [XmlAttribute("TABLE_NAME")]
    public string Table_Name { get; set; }
}

And then you deserialize with:

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

using (var file = File.OpenText("sample.xml"))
{
    var data = (SerializableContainer)serializer.Deserialize(file);

    // ... 
}

Upvotes: 7

Related Questions