C#XML Deserialize对象为空

时间:2014-07-09 13:57:46

标签: c# xml deserialization

我正在尝试将XML字符串反序列化为对象。

对象是:

[Serializable]
public class THIRD_PARTY_CONFIRMATION
{
    public string thirdPartyId { get; set; }
}

我试图运行的代码是:

var response = "<?xml version='1.0' encoding='UTF-8' ?><THIRD_PARTY_CONFIRMATION thirdPartyId = \"3984000\" />";
using (var stream = new StringReader(response))
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(THIRD_PARTY_CONFIRMATION));
    var temp = (THIRD_PARTY_CONFIRMATION)xmlSerializer.Deserialize(stream);
}

如果我在Visual Studio中检查temp,则thirdPartyId为null。我做错了什么?

1 个答案:

答案 0 :(得分:3)

您需要将属性XmlAttribute添加到thirdPartyId

[Serializable]
public class THIRD_PARTY_CONFIRMATION
{
    [XmlAttribute]
    public string thirdPartyId { get; set; }
}

否则它将开始寻找元素的值而不是属性。