2

我尝试反序列化 xml 文件:

<?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>

我的反序列化类代码如下所示:

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

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

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

当我尝试反序列化 xml 文件时,我总是没有错误,并且 Item 和 Table_Name 等于 null。为什么?

谢谢重播

4

2 回答 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; }
}

然后你反序列化:

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

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

    // ... 
}
于 2013-10-02T11:10:00.010 回答
1

如果有人需要,请在这里留下一个更完整的示例:http: //davidsonsousa.net/en/post/serializedeserialize-objects-to-xml-with-c

干杯!

于 2015-01-05T00:41:15.893 回答