我在尝试反序列化某些 XML 时遇到了真正的麻烦,希望有人能提供一些帮助。我已经阅读了很多类似的帖子,但我无法解决这个问题。
我正在尝试反序列化的 XML
<register-account success="false">
<user-name>xxxxx</user-name>
<password>fghgh</password>
<email>test@example.com</email>
<error>
<errorcode>120</errorcode>
<errormessage>The password is invalid</errormessage>
</error>
</register-account>
我试图反序列化为:
[Serializable, XmlRoot(ElementName = "register-account", Namespace = "MyNamespace")]
[XmlType("register-account")]
public class RegisterAccountResponse
{
[XmlAttribute("success")]
public bool Success { get; set; }
/// <summary>
/// Gets or sets the Tennant email address
/// </summary>
[XmlElement("email")]
public string Email { get; set; }
/// <summary>
/// Gets or sets the tennant password
/// </summary>
[XmlElement("password")]
public string Password { get; set; }
/// <summary>
/// Gets or sets the Tennant username
/// </summary>
[XmlElement("user-name")]
public string Username { get; set; }
/// <summary>
/// A Tenant Portal error relating to the RegisterAccountRequest
/// </summary>
[XmlElement("error")]
public QubeError Error;
}
反序列化方法
public static T Deserialize<T>(string data) where T : class
{
if (data == null)
{
return null;
}
if (data.Trim().Length == 0)
{
return null;
}
var ser = new XmlSerializer(typeof(T));
using (var sr = new StringReader(data))
{
return (T)ser.Deserialize(sr);
}
}
反序列化方法调用
var data = Helper.Deserialize<RegisterAccountResponse>(xml);
例外:
XML 文档 (1, 2) 中存在错误。---> System.InvalidOperationException:不是预期的。在 Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderData.Read5_data()
内部异常如下:
<register-account xmlns=''> was not expected.