2

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

2
  • More code would be usefull. My guess looking at the provided info is: You are not specifying the "OBJECTS" element. You're class defines "XmlFile/@ITEM" and "XmlFile/@TABLE_NAME" whereas the XML has an "OBJECTS" element in between. Commented Oct 2, 2013 at 11:00
  • I see the use of "Serializable" attribute (used for the RunTime serializers) AND the use of "XmlRoot/XmlAttribute" attributes which are intended for the XmlSerializer. Which one are you using? Commented Oct 2, 2013 at 11:01

2 Answers 2

7
[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);

    // ... 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Now I know where i made mistakes.
1

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

Cheers!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.