将XML字符串反序列化为对象C#

时间:2018-09-18 09:43:29

标签: c# xml serialization

我有这堂课

[Serializable]
[XmlRoot(ElementName = "Cat")]
public class Cat
{
    /// <summary>
    /// Gets the cat name
    /// </summary>
    [XmlAttribute("CatName")]
    public string CatName{ get; }

    /// <summary>
    /// Gets the cat origin
    /// </summary>
    [XmlAttribute("CatOrigin")]
    public string CatOrigin{ get; }
}

我正在尝试将此字符串反序列化为我的对象'Cat'

string myString= "<Cat CatName= \"A\" CatOrigin=\"B\" />";

我正在使用此方法反序列化:

 public Cat DeserializeCat(string def)
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(Cat));
        TextReader reader = new StringReader(def);
        object obj = deserializer.Deserialize(reader);
        Cat XmlData = (Cat)obj;
        reader.Close();
        return XmlData;
    }

但是我一直在为每个参数获取一个具有空值的对象。 您有什么主意,为什么我不能从字符串到对象获取值?

1 个答案:

答案 0 :(得分:2)

现在,您在Cat类中的属性是只读的,因为它仅包含get

要将数据存储到各自的属性中,您需要使用set

[Serializable]
[XmlRoot(ElementName = "Cat")]
public class Cat
{
    /// <summary>
    /// Gets the cat name
    /// </summary>
    [XmlAttribute("CatName")]
    public string CatName{ get; set; }

    /// <summary>
    /// Gets the cat origin
    /// </summary>
    [XmlAttribute("CatOrigin")]
    public string CatOrigin{ get; set; }
}

POC:

enter image description here

参考:set(C# reference)