【问题标题】:Deserialize an XML string to an object C#将 XML 字符串反序列化为对象 C#
【发布时间】:2018-09-18 09:43:28
【问题描述】:

我有这门课

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

但我总是得到一个每个参数都为空值的对象。 你知道为什么我没有从我的字符串中获取值到我的对象吗?

【问题讨论】:

    标签: c# xml serialization


    【解决方案1】:

    现在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:

    参考:set(C# reference)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-30
      • 1970-01-01
      相关资源
      最近更新 更多