简体   繁体   English

C#XML反序列化对象为空

[英]C# XML Deserialize object is empty

I am attempting to deserialize an XML string to an object. 我正在尝试将XML字符串反序列化为对象。

The object is: 对象是:

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

and the code I am trying to run is: 我试图运行的代码是:

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

If I inspect temp in Visual Studio, thirdPartyId is null. 如果我在Visual Studio中检查温度,则thirdPartyId为null。 What am I doing wrong? 我究竟做错了什么?

You need to add the property XmlAttribute to the thirdPartyId 您需要将属性XmlAttribute添加到thirdPartyId

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

otherwise it'll start looking for a value of the element and not an attribute. 否则,它将开始寻找元素的值而不是属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM