【问题标题】:XML Deserialization is returning null for an xml attribute but is returning the correct Xml textXML 反序列化为 xml 属性返回 null,但返回正确的 Xml 文本
【发布时间】:2017-10-12 16:18:42
【问题描述】:

下面我有以下对象:

[XmlRoot("ExampleObject")]
public class ExampleObject
{
    [XmlElement("element1")]
    public long element1{ get; set; }

    [XmlElement("element2")]
    public string element2{ get; set; }

    [XmlElement("element3")]
    public string element3{ get; set; }

    [XmlElement("element4")]
    public ExampleObject2 element4{ get; set; }
}

[Serializable()]
public class ExampleObject2
{
    [XmlText]
    public string Value { get; set; }

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

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

以及以下 XML:

<c:ExampleObject>
   <c:element1>
        ...
   </c:element1>
   <c:element2>
          ...
   </c:element2>
   <c:element3>
          ...
   </c:element3>
   <c:element4 z:Ref="953" i:nil="true"/> <!--- or this <c:Status z:Id="953">...</c:element4> -->
</ExampleObject>

除了element4 内部ExampleObject2IdRef 为空,而Value 内部具有正确值外,我能够完美地获取我的对象。

我希望ExampleObject2 总是有一个Value,它要么为空,要么为它应该具有的值。我希望 IdRef 成为 element4 中属性的值,具体取决于 element4 是否具有该属性。

我想知道我是否遗漏了什么?

我还尝试为像 [XmlAttribute("Id")] 这样的 XMLElement 标签添加特定名称,但这似乎没有任何作用。我也尝试过包含像 [XmlAttribute("z:Id")] 这样的命名空间,但这会导致错误。

我也尝试将 IsNullable 放在 element4 XMLElement 标记中,但对于具有 nil="true" 的 XML 元素,它会使整个 ExampleObject2 为空,这并不是我想要的。

我已经查看了以下问题并遇到了同样的问题。

how to deserialize an xml node with a value and an attribute using asp.net serialization

谢谢

【问题讨论】:

  • 你在哪里定义前缀“c”?还应该有前缀“z”的定义。
  • “Ref”和“Id”属性在哪里?我只看到“z:Ref”和“i:nil”。还可以尝试向该元素添加文本,这样可以吗?
  • 顺便说一下,XML 看起来好像是用DataContractSerializerpreserveObjectReferences = true 生成的,而不是用XmlSerializer 生成的。有关示例,请参见 .net XML Serialization - Storing Reference instead of Object CopyIsReference property in data contract。也许您应该切换到该序列化程序? minimal reproducible example 显示了我可以肯定地说的实际命名空间。
  • @GeorgeBirbilis 我最终像你说的那样用 Nil 属性修复了它,并将它与 dbc 解决方案一起使用来手动命名 z: 和 c: 来自的命名空间。我只是做其中之一,而不是两者结合。谢谢!
  • 很好 - 顺便说一句,我认为您可以为自己的问题添加答案,尽管我不确定(可能在 meta.stackoverflow.com 上有人问过这样做)。跨度>

标签: c# xml deserialization xml-deserialization


【解决方案1】:

我最终用@GeorgeBirbilis 所说的 Nil 属性修复它,并将它与@dbc 的解决方案一起使用,以手动命名 z: 和 c: 来自的命名空间。我只是做其中之一,而不是两者结合。谢谢大家的帮助。

[XmlAttribute(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/")]
public int Id { get; set; }

[XmlAttribute(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/")]
public int Ref { get; set; }

private bool _nil;

[XmlAttribute("nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public bool Nil
{
    get
    {
        return _nil;
    }
    set
    {
        _nil = value;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    相关资源
    最近更新 更多