【问题标题】:Why XmlSerializer cannot deserialize xml with schema specified in the root element为什么 XmlSerializer 无法使用根元素中指定的架构反序列化 xml
【发布时间】:2014-03-26 15:14:21
【问题描述】:

我有一个和他类似的xml

<ns2:person xmlns:ns2="somenamespace">
  <firstName>John</firstName>
  <lastName>John</lastName>
</ns2:person>

我尝试像这样反序列化它:

var ser = new XmlSerializer(typeof(Person));
b = (Person)ser.Deserialize(new StringReader(xml));

T 是一个类

[XmlRoot(Name = "person", Namespace = "somenamespace")]
public class Person {
    [XmlElement(ElementName = "firstName")]
    public string fistName {get;set;}
    [XmlElement(ElementName = "lastName")]
    public string lastName {get;set;}
}

在创建对象后,它的属性仍然为空

如果您删除 &lt;person&gt;... 之类的架构,同样的示例也有效

不幸的是我无法控制源xml,除了更改xml字符串(如果有的话)之外,我需要了解背后的原因并找出解决方法。

【问题讨论】:

  • 如果要在 XML 中使用命名空间,则需要在反序列化代码中考虑到这一点。看看:stackoverflow.com/a/1545123/1726343.
  • 因为ns前缀没有定义。这个 XML 没有意义。
  • 我的错误应该是ns2

标签: c# .net xml xml-deserialization


【解决方案1】:

将 Namespace = "" 添加到 XmlElement 属性

[XmlRoot(ElementName = "person", Namespace = "somenamespace")]
public class Person {
  [XmlElement(ElementName = "firstName", Namespace = "")]
  public string fistName { get; set; }
  [XmlElement(ElementName = "lastName", Namespace = "")]
  public string lastName { get; set; }
}    

【讨论】:

    猜你喜欢
    • 2012-07-25
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 2020-12-09
    • 2014-12-24
    相关资源
    最近更新 更多