C# Deserialization xml file

青春壹個敷衍的年華 提交于 2019-12-31 03:42:06

问题


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


回答1:


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

    // ... 
}



回答2:


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

Cheers!



来源:https://stackoverflow.com/questions/19135291/c-sharp-deserialization-xml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!