【问题标题】:Restore object from XML with a duplicated XmlElementAttribute name使用重复的 XmlElementAttribute 名称从 XML 恢复对象
【发布时间】:2014-01-23 10:08:43
【问题描述】:

我有一个具有这种结构的对象:

    public class XMLTagDataSection
    {
        [XmlElement("Type", Order=1)]
        public EnuDataType XML_type  { get; set; }

        [XmlElement("Value", IsNullable = false, Order = 2)]
        public string XML_Value      { get; set; }

        [XmlElement("Value", IsNullable = false, Order = 3)]
        public XMLTagValue Tag_Value { get; set; }
    }

    public class XMLTagValue
    {
        [XmlElement("Variable", IsNullable = false, Order = 4)]       
        public int   Variable { get; set; }
    }

要生成这样的 XML 文件:

案例#1:

    <Data>
      <Offset>0</Offset>
      <Type>ASCII</Type>          
      <Value>
        <Variable>1</Variable>
      </Value>
    </Data>

案例#2:

    <Data>
      <Offset>0</Offset>
      <Type>ASCII</Type>          
      <Value>TestString</Value>
    </Data>

我的实际问题是我无法将两个不同的值标签正确反序列化回一个对象。

【问题讨论】:

  • 简短回答:不要使用此架构。
  • 虽然这个问题很有趣,但我需要同意@user2864740。
  • 您是否尝试过在一个 XML 结构中包含两个 Value 元素?如果您只提供一个,它可能永远不会起作用(反序列化器如何知道您正在寻找哪一个)。最好的解决方案是将元素名称区分为可以分别区分两者的名称。
  • 中长回答:实现此目的的一种方法是拥有一个 single Value-named 类型为 XmlNode[] or 的属性实现IXmlSerializable 的类型。然后,您有责任酌情提供所需的自定义映射(例如 Value 节点的内容)。非序列化 (XmlIgnore) 属性可以充当包装访问器。
  • 先尝试创建一个xsd。如果您能够创建一个验证您的 xml 的程序,那么(除了某些情况)您可以使用 VS 提示符中的 xsd.exe 自动生成整个 xml 处理。我会建议这种方法,因为您可能会从中受益,而不是编写可以更好地自动生成的代码。

标签: c# xml-serialization xmlserializer


【解决方案1】:

我自己的想法是区分价值标签是这样的;

    [XmlInclude(typeof(XMLTagValue)), XmlInclude(typeof(XMLValue))]
    public class XMLTagDataSection
    {
        [XmlElement("Offset")]
        public int XML_Offset        { get; set; }

        [XmlElement("Type")]
        public EnuDataType XML_type  { get; set; }

        public object Tag_Value      { get; set; }
    }

    public class XMLVariable
    {
        [XmlElement("Variable", IsNullable = false)]       
        public int   Variable { get; set; }
    }

    public class XMLValue
    {
        [XmlElement("Value", IsNullable = false)]
        public string XML_Value      { get; set; }
    }

但在这种情况下,对象 Tag_Value 成为 XML 文件中自己的标签。 有没有办法启用 xmlserializer 的这种行为

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 2012-11-11
    • 2018-02-08
    • 2016-10-30
    相关资源
    最近更新 更多