将复杂类型XML转换为类

时间:2014-04-11 15:52:59

标签: c# xml class deserialization setter

我想知道如何将这个复杂类型的xml转换为模型或类?

我有下面的尝试,我想知道是否有人可以为我检查一下?

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<lot_information lot_exp_date="XXXX-XX-XX" lot_number="123456">
<components> 
<component control="A" ref="A" family="XXXXX" component="12" id="1A1">
<target>42</target> 
<min>12</min >
<max>90</max>
<number>10</number> 
</component>
<component control="A" ref="A" family="XXXXX" component="13" id="1A2B3C">
<target>42</target>
<min>12</min>
<max>90</max>
<number>10</number>
</component>
</components> 
<families>
<control family="XXXXX" ctrl="ctrlA"/> 
<control family="XXXXX" ctrl="ctrlB"/>
<control family="XXXXX" ctrl="ctrlC"/> 
<control family="XXXXX" ctrl="ctrlD"/> 
</families> </lot_information>

这是我的模特课:

[Serializable]
public class LotInformation
{
    public string exp_date { get; set; }
    public Array[] lot_information { get; set; } 
    public int lot_number {get; set;} 

}
[Serializable]
public class Components {

    public Array[] ComponentControl { get; set; }
    public string ref { get; set; }
    public string family { get; set; }
    public int component { get; set; }
    public string id { get; set; }

}
[Serializable]
public class Family
{
    private string[] controlFamily { get; set; }
    private string ctrl { get; set; }

} 

如果我使用数组来保持XML文件的结构不是那种格式,那么请仔细检查是否有意义。

最终,这将被反序列化,所以我想知道上述是否有意义。

编辑:请不要评论自动化工具来帮助我。它们使它变得更加复杂。我想编写干净的代码,看看我的内容是否有意义。自动化工具为我提供无符号整数,空名称空间和其他不必要的改进。

2 个答案:

答案 0 :(得分:0)

您可以使用XSD.EXE工具

  1. Xsd yourxml.xml
  2. 获取yourxml.xsd文件。然后

    1. Xsd yourxml.xsd / classes
    2. 这将自动生成类文件。

答案 1 :(得分:0)

您的xml数据目前无效,将<Components>更改为<components>应该有效。

如果您有Visual Studio 2013,则可以将XML粘贴到类中。 看起来很丑,但至少你应该确定它是正确的。

复制XML数据,然后在Visual Studio中复制。 编辑 - &gt;粘贴特殊 - &gt;将XML粘贴为类

修改

更新了代码示例 这是我清理自动生成的代码时得到的, 没有信息字段是否来自XML中的属性。这可以使用属性的注释进行更新。

我通过将类型简化为string或int来清理代码,并使用自动属性而不是显式属性,并删除了自动生成的xml属性。

[Serializable]
public class Lot_information {    
    public Component[] components { get; set; }
    public Control[] families { get; set; }
    public string lot_exp_date { get; set;}
    public int lot_number { get; set;}
}
[Serializable]
public class Component {    
    public int target { get; set; }    
    public int min { get; set; }    
    public int max { get; set; }    
    public int number { get; set; }
    public string control { get; set; }
    public string @ref { get; set; }
    public string family { get; set; }
    public int component { get; set; }
    public string id { get; set; }
}
[Serializable]
public class Control {
    public string family { get; set; }
    public string ctrl { get; set; }
}