【问题标题】:c# Deserialize custom class with nested classesc# 使用嵌套类反序列化自定义类
【发布时间】:2012-11-18 20:59:09
【问题描述】:

我正在尝试将我的 xml 反序列化为一个自定义对象,我已经接近了,但是没有填充最嵌套的元素,而所有的父母都工作正常。

这是反序列化过程的 xml 和类:

<?xml version="1.0" encoding="utf-8" ?>
<dataMapping>
  <documentType attr1="blah" attr2="blah2" attr3="blah3">
    <indexFields>
      <indexField name1="field1A" name2="field1B" type="int" />
      <indexField name1="field2A" name2="field2B" type="int" />
      <indexField name1="field3A" name2="field3B" type="int" />
    </indexFields>
  </documentType>
  <documentType attr1="asdf" attr2="asdf2" attr3="asdf3">
    <indexFields>
      <indexField name1="field1A" name2="field1B" type="int" />
      <indexField name1="field2A" name2="field2B" type="int" />
      <indexField name1="field3A" name2="field3B" type="int" />
    </indexFields>
  </documentType>
</dataMapping>


[XmlRoot("dataMapping")]
public class dataMapping
{
    [XmlElement("documentType")]
    public List<DocumentType> DocumentTypes{ get; set; }

    public dataMapping() { }
}

[XmlRoot("documentType")]
public class DocumentType
{
    [XmlAttribute("attr1")]
    public string Area { get; set; }

    [XmlAttribute("attr2")]
    public string Cabinet { get; set; }

    [XmlAttribute("attr3")]
    public string SearchGroup { get; set; }

    [XmlElement("indexFields")]
    public List<IndexField> IndexFields{ get; set; }

    public DocumentType() { }
}

[XmlRoot("indexField")]
public class IndexField
{
    [XmlAttribute("name1")]
    public string Name1 { get; set; }

    [XmlAttribute("name2")]
    public string Name2 { get; set; }

    [XmlAttribute("type")]
    public string DataType { get; set; }

    public string ObjectValue { get; set; }

    public IndexField() { }
}

因此,当通过反序列化创建我的自定义对象时,除了索引字段及其关联属性之外,所有内容都在填充。我在设置那个类时哪里错了?

【问题讨论】:

    标签: c# serialization xml-serialization deserialization xml-deserialization


    【解决方案1】:

    尝试添加XmlArrayItem 应该会有所帮助

    [XmlArrayItem(typeof(IndexField))]
    public List<IndexField> IndexFields{ get; set; }
    

    【讨论】:

      【解决方案2】:

      明白了。我还需要一个名为“IndexFields”的类(基于我构建 xml 的方式),然后它包含一个“IndexField”列表....只是缺少一个级别。

      [XmlRoot("indexFields")]
      public class IndexFields
      {
          [XmlElement("indexField")]
          public List<IndexField> NestedIndexFields { get; set; }
      
          public IndexFields() { }
      }
      

      【讨论】:

        猜你喜欢
        • 2023-04-01
        • 2012-05-08
        • 2013-12-30
        • 1970-01-01
        • 1970-01-01
        • 2018-08-01
        • 1970-01-01
        • 2015-01-26
        • 1970-01-01
        相关资源
        最近更新 更多