[英]How to Deserialize an xml element with only attributes in C#?
I am using System.Xml.Serialization.XmlSerializer class.I need to Deserialize the following XML in C#: 我正在使用System.Xml.Serialization.XmlSerializer类。我需要在C#中反序列化以下XML:
<message from="abc" to="xyz" xml:lang="en" id="Vx4Ix-14" type="chat">
<received xmlns="urn:xmpp:receipts" id="9beea4d7-aa1e-4f3c-929c-712b56164b63"/>
</message>
Following is my Class to deserialize it : 以下是我的课程来反序列化它:
[XmlRoot(ElementName = "message")]
public class Message
{
[XmlAttribute(AttributeName = "type")]
public string Type { get; set; }
[XmlAttribute(AttributeName = "from")]
public string From { get; set; }
[XmlAttribute(AttributeName = "to")]
public string To { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
[XmlAttribute(AttributeName = "xml:lang")]
public string Language { get; set; }
[XmlElement(ElementName = "received", Namespace = "urn:xmpp:receipts")]
public Received Received { get; set; }
}
public class Received
{
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
The "received" xml element has only attributes and I want te deserialize that element to get "id" value of that element. “已接收” xml元素仅具有属性,我想对该元素反序列化以获得该元素的“ id”值。 But when I use the above class to Deserialize , I get all the values except "id" attribute value of "received" xml element.
但是,当我使用上述类对Deserialize进行反序列化时,将获得除“ received” xml元素的“ id”属性值以外的所有值。 I get the value of Received property as null.
我将Received属性的值设置为null。
Please let me know what is wrong with my class? 请让我知道我班上怎么了?
This is my Deserializer Method: 这是我的反序列化方法:
public static T Deserialize<T>(string xml)
{
T deserializedObject = default(T);
try
{
var serializer = new XmlSerializer(typeof(T));
using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
deserializedObject = (T)serializer.Deserialize(memoryStream);
}
return deserializedObject;
}
catch (Exception)
{
return deserializedObject;
}
}
Your class looks good and also works for me. 您的班级看起来不错,对我也有用。 Maybe you're not using the deserializer correctly!?
也许您未正确使用解串器!? I successfully tried it with your XML like this:
我成功使用您的XML尝试了如下操作:
var serializer = new XmlSerializer(typeof(Message));
var message = (Message)serializer.Deserialize(
new FileStream(@"C:\Users\homann.k\Desktop\test.xml", FileMode.Open, FileAccess.Read));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.