我将如何将这个 XML 反序列化为 C# 中的一个类?
<?xml version="1.0" encoding="UTF-8"?>
<root>
<infos>
</infos>
<users>
<user userID="1" userRole="1" channelID="0"><![CDATA[Test_User]]></user>
<user userID="2" userRole="0" channelID="0"><![CDATA[Test_User_2]]></user>
</users>
<messages>
<message id="349992" dateTime="Sat, 01 Sep 2012 18:29:48 +0000" userID="1" userRole="1" channelID="0">
<username><![CDATA[Test_User]]></username>
<text><![CDATA[Test Message]]></text>
</message>
<message id="349993" dateTime="Sat, 01 Sep 2012 18:29:50 +0000" userID="2" userRole="0" channelID="0">
<username><![CDATA[Test_User_2]]></username>
<text><![CDATA[Test Message 2]]></text>
</message>
</messages>
</root>
我之前使用 XML 进行了一些序列化和反序列化,但由于某种原因,我无法为使用此 XML 的类找到正确的结构。
到目前为止,这就是我所拥有的一切,但它不起作用。任何人都可以构建这些类以使用上述 XML 吗?
[Serializable]
public class User
{
[XmlAttribute("userID")]
public object UserId;
[XmlAttribute("userRole")]
public object UserRole;
[XmlAttribute("channelID")]
public object ChannelId;
}
[Serializable]
public class Message
{
[XmlAttribute("id")]
public object Id;
[XmlAttribute("dateTime")]
public object DateTime;
[XmlAttribute("userID")]
public object UserId;
[XmlAttribute("userRole")]
public object UserRole;
[XmlAttribute("channelID")]
public object ChannelId;
[XmlElement("username")]
public object Username;
[XmlElement("text")]
public object Text;
}
[Serializable, XmlRoot("root")]
public class Root
{
[XmlElement("infos")]
public object Infos;
[XmlElement("users")]
public List<User> Users;
[XmlElement("messages")]
public List<Message> Messages;
}
它抛出这个错误。
System.InvalidOperationException was unhandled by user code
Message=There was an error reflecting type 'ConsoleApplication.Client.Root'.
Message=There was an error reflecting field 'Users'.
Message=There was an error reflecting type 'ConsoleApplication.Client.User'.
Message=There was an error reflecting field 'UserId'.
Message=Cannot serialize member 'UserId' of type System.Object. XmlAttribute/XmlText cannot be used to encode complex types.