【问题标题】:Deserialize xml element string反序列化 xml 元素字符串
【发布时间】:2012-12-07 04:52:58
【问题描述】:

我有这个 XML 元素字符串:

<person name="jhon smith" birth="11/10/1988" username="ilearn" password="123"/>

现在我想将其反序列化为其各自的对象:

public class CancelCardResponse
{
    public string name { get; set; }
    public string birth { get; set; }
    public string username { get; set; }
    public string password { get; set; }
}

我正在使用类似这样的代码:

XmlSerializer deserializer = new XmlSerializer(typeof(Person));
StringReader reader = new StringReader(myxmlelementstring);

var a = deserializer.Deserialize(reader); // fail!

错误内容如下:

System.InvalidOperationException {"XML 文档有错误 (1,2)."}

是否可以像上面那样反序列化 XML 元素字符串?
有什么我可以添加到我的 XML 元素字符串中以使用 C# 反序列化器的吗?

【问题讨论】:

  • 这个 xml 是否被 .NET 序列化了?
  • 另外,为什么类在您的代码中称为CancelCardResponse 而不是Person
  • 您需要向您的类和属性添加属性以将它们映射到 XML 文档架构。
  • 这是我从 web 服务获取的 xml 字符串

标签: c# xml string deserialization


【解决方案1】:

试试这样:

public class person
{
    [XmlAttribute]
    public string name { get; set; }

    [XmlAttribute]
    public string birth { get; set; }

    [XmlAttribute]
    public string username { get; set; }

    [XmlAttribute]
    public string password { get; set; }
}

我没有编译或测试它,距离我使用XmlSerializer 用户已经有一段时间了,但这应该能让你到达那里或接近它。

【讨论】:

    【解决方案2】:

    将您的 CancelCardResponse 类重命名为 Person 并使用 [XmlAttribute("Attr Name as in XML")] 注释它的属性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2011-06-24
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多