【发布时间】:2015-07-21 11:30:53
【问题描述】:
我正在尝试将 xml 字符串反序列化为 c# 对象。这是消息:
<message from='test1@localhost' to='test2@localhost'><result xmlns='urn:xmpp:mam:tmp' id='A6QV1I4TKO81'><forwarded xmlns='urn:xmpp:forward:0'><delay xmlns='urn:xmpp:delay' from='test1@localhost' stamp='2015-07-21T09:12:09Z'></delay><message type='mchat'><subject/><body/></message></forwarded></result></message>
这就是类
public class Delay {
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
[XmlAttribute(AttributeName="from")]
public string From { get; set; }
[XmlAttribute(AttributeName="stamp")]
public string Stamp { get; set; }
}
public class Active {
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
}
public class XmppMessage {
[XmlElement(ElementName="body")]
public string Body { get; set; }
[XmlAttribute(AttributeName="lang")]
public string Lang { get; set; }
[XmlAttribute(AttributeName="type")]
public string Type { get; set; }
[XmlAttribute(AttributeName="id")]
public string Id { get; set; }
[XmlAttribute(AttributeName="to")]
public string To { get; set; }
}
public class Forwarded {
[XmlElement(ElementName="delay")]
public Delay Delay { get; set; }
[XmlElement(ElementName="message")]
public XmppMessage Message { get; set; }
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
}
public class Result {
[XmlElement(ElementName="forwarded")]
public Forwarded Forwarded { get; set; }
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
[XmlAttribute(AttributeName="id")]
public string Id { get; set; }
}
[XmlRoot(ElementName="message")]
public class MessageHistory {
[XmlElement(ElementName="result")]
public Result Result { get; set; }
[XmlAttribute(AttributeName="from")]
public string From { get; set; }
[XmlAttribute(AttributeName="to")]
public string To { get; set; }
}
这是反序列化的代码:
MessageHistory messageNode;
XmlSerializer serializer = new XmlSerializer(typeof(MessageHistory));
using (StringReader reader = new StringReader(message))
{
messageNode = (MessageHistory)(serializer.Deserialize(reader));
}
对象属性“from”和“to”没问题,但“Result”返回空值。我无法理解我在这里错过了什么......
【问题讨论】:
-
将 [XmlRoot(ElementName="..")] 添加到所有类。该名称区分大小写,因此您的类名称为“Forwarded”,标签名称为“forwarded”。添加 XmlRoot 将允许标记为小写,类名为大写。
-
MessageHistory 类上的 XmlRoot 就足够了,问题出在命名空间...还是谢谢你
标签: c# xml xmpp deserialization