对象

时间:2017-04-11 13:56:51

标签: c# .net xml

我想将一个简单的XML文件序列化为object:

    <?xml version="1.0"?>

-<Tables>


-<StaticGroups>


-<StaticGroup Name="111">


-<Table>

<TableName>Table1 Name</TableName>

<TableTag>Table1 Tag</TableTag>

</Table>


-<Table>

<TableName>Table2 Name</TableName>

<TableTag>Table2 Tag</TableTag>

</Table>

</StaticGroup>


-<StaticGroup>


-<Table>

<TableName>Table3 Name</TableName>

<TableTag>Table3 Tag</TableTag>

</Table>

</StaticGroup>

</StaticGroups>

</Tables>

以下是课程:

 [XmlRoot("Tables")]
    public class TablesXML
    {
        public TablesXML()
        {
            StaticTablesGroups = new List<StaticTablesGroup>();
        }


        [XmlArray("StaticGroups")]
        [XmlArrayItem("StaticGroup", typeof(StaticTablesGroup))]
        public List<StaticTablesGroup> StaticTablesGroups { get; set; }

    }

    public class StaticTablesGroup
    {
        public StaticTablesGroup()
        {
            GroupTables = new List<GroupTable>();
        }

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

        [XmlArray("StaticGroup")]
        [XmlArrayItem("Table", typeof(GroupTable))]
        public List<GroupTable> GroupTables { get; set; }
    }


    public class GroupTable
    {

        [XmlElement("TableName")]
        public string Name { get; set; }
        [XmlElement("TableTag")]
        public string Tag { get; set; }
    }

使用Name属性正确创建StaticGroup列表。

问题是Table / s(TableName和TableTag)由于某种原因未被序列化。我做错了什么?

由于

编辑#1 谢谢Marc帮助解决问题#1

现在我正在尝试在另一个StaicGroup中添加StaticGroup      

-<Tables>


 -<StaticGroups>


-<StaticGroup Name="111">


-<Table>

<TableName>Table1 Name</TableName>

<TableTag>Table1 Tag</TableTag>

</Table>
-<StaticGroup Name="111.1">


-<Table>

<TableName>Table1.1 Name</TableName>

<TableTag>Table1.1 Tag</TableTag>

</Table>
</StaticGroup>
</StaticGroup>

反序列化工作正常,但嵌套不能从XML获取数据

修改了StaticTablesGroup类:

public class StaticTablesGroup
    {
        public StaticTablesGroup()
        {
            GroupTables = new List<GroupTable>();
            StaticTablesGroups = new List<StaticTablesGroup>();
        }

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

        //[XmlArray("StaticGroup")]
        [XmlElement("Table", typeof(GroupTable))]
        public List<GroupTable> GroupTables { get; set; }



        [XmlElement("StaticGroup", typeof(StaticTablesGroup))]
        public List<StaticTablesGroup> StaticTablesGroups { get; set; }        
    }

然而,正如Marc建议的那样,我检查了Serialize,并且它工作正常

1 个答案:

答案 0 :(得分:1)

您已经 <StaticGroup>内,因此您不需要[XmlArray("StaticGroup")]。相反,在列表中使用XmlElement,这使得它将<Table>的每个实例作为列表中的项处理,而不包含列表本身的包装元素:

[XmlElement("Table")]
public List<GroupTable> GroupTables { get; set; }