从分层类结构创建XML

时间:2012-02-09 17:30:57

标签: c# .net winforms visual-studio-2010 xml-serialization

我正在尝试基于类设置创建XML文件。我无法让它工作,目前我没有得到任何错误或异常只是意外的结果。

我期待这样的事情

<armyListing><army name="">
<unit-category name="">
<unit-type name="">
<unit name="" composition="" weapon-skill="" etc></unit>
</unit-type>
<unit-type name="">
<unit name="" composition="" weapon-skill="" etc></unit>
</unit-type>
</unit-category>
</army>
</armyListing>

但我得到<armyListing><army/></armyListing>

我认为我可能已经将XML扩展到了太长的篇幅,因此我尝试一次一个地评论出最高级别的类,但仍然得到相同的结果。

非常感谢被指向正确的方向,谢谢!

namespace ThereIsOnlyRules
{
[Serializable]
public class ArmyListing
{

    //[XmlElement("army")]
    //public string name { get; set; }
    [XmlArray]
    public List<Army> army { get; set; }

    public void SerializeToXML(ArmyListing armyListing)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ArmyListing));
            TextWriter textWriter = new StreamWriter(@"C:\Test\40k.xml");
            serializer.Serialize(textWriter, armyListing);
            textWriter.Close();
        }
        catch (Exception ex) { }
    }
}

[Serializable]
public class Army
{
    //public Army();

    //[XmlAttribute]
    [XmlArray("unit-category")]
    public List<UnitCategory> unitCategory { get; set; }
    [XmlAttribute("name")]
    public string armyName { get; set; }
}

[Serializable]
public class UnitCategory
{
    //public UnitCategory();

    [XmlArray("unit-type")]
    public List<UnitType> unitType { get; set; }
    [XmlAttribute("name")]
    public string unitCategoryName { get; set; }
}

[Serializable]
public class UnitType
{
    //public UnitType();

    [XmlArray("unit")]
    public List<Unit> unit { get; set; }
    [XmlAttribute("name")]
    public string unitTypeName { get; set; }
}

[Serializable]
public class Unit
{
    //public Unit();

    [XmlAttribute("name")]
    public string unitName { get; set; }
    [XmlAttribute("composition")]
    public string compsition { get; set; }
    [XmlAttribute("weapon-skill")]
    public string weaponSkill { get; set; }
    [XmlAttribute("ballistic-skill")]
    public string ballisticSkill { get; set; }
    [XmlAttribute("strength")]
    public string strength { get; set; }
    [XmlAttribute("toughness")]
    public string T { get; set; }
    [XmlAttribute("wounds")]
    public string wounds { get; set; }
    [XmlAttribute("initiative")]
    public string initiative { get; set; }
    [XmlAttribute("attacks")]
    public string attacks { get; set; }
    [XmlAttribute("leadership")]
    public string leadership { get; set; }
    [XmlAttribute("saving-throw")]
    public string saveThrow { get; set; }
    [XmlAttribute("armour")]
    public string armour { get; set; }
    [XmlAttribute("weapons")]
    public string weapons { get; set; }
    [XmlAttribute("special-rules")]
    public string specialRules { get; set; }
    [XmlAttribute("dedicated-transport")]
    public string dedicatedTransport { get; set; }
    [XmlAttribute("options")]
    public string options { get; set; }
}


}
namespace ThereIsOnlyRules
{
public partial class Form1 : Form
{
    //ArmyListing armyListing = new ArmyListing();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        ArmyListing armyListing = new ArmyListing();
        Army army = new Army();
        UnitCategory unitCategory = new UnitCategory();
        UnitType unitType = new UnitType();
        Unit unitList = new Unit();

        armyListing.army = new List<Army>();
        army.unitCategory = new List<UnitCategory>();
        unitCategory.unitType = new List<UnitType>();
        unitType.unit = new List<Unit>();

        army.armyName = "Tyranid";

        unitCategory.unitCategoryName = "Troops";
        unitType.unitTypeName = "Infantry";

        unitList.armour = "Chitin";
        unitList.attacks = "3";
        unitList.ballisticSkill="100";
        unitList.compsition="20";
        unitList.dedicatedTransport = "No";
        unitList.initiative = "3";
        unitList.leadership = "5";
        unitList.options = "8";
        unitList.saveThrow = "6+";
        unitList.specialRules ="None";
        unitList.strength = "3";
        unitList.T = "4";
        unitList.unitName = "Hornmagant";
        unitList.weapons = "Many";
        unitList.weaponSkill = "3";
        unitList.wounds = "1";

        //List<Unit> unit = new List<Unit>();
        //List<UnitType> unitType = new List<UnitType>();
        //List<UnitCategory> unitCategory = new List<UnitCategory>();
        //List<Army> army = new List<Army>();

        //Dictionary<ArmyListing, Army> armylist = new Dictionary<ArmyListing,Army>();

        armyListing.SerializeToXML(armyListing);
    }
}

2 个答案:

答案 0 :(得分:2)

查看您的对象创建代码。你新建了所有这些对象,但是你永远不会将它们绑在一起。最终发生的事情是您将完全空的ArmyListing对象传递给序列化程序。这是编码的正确行为。

添加

armyListing.army.Add(army)

你会看到你开始得到一些输出。

答案 1 :(得分:1)

此任务的非常有用的功能是Object and Collection Initializers,它是自C#3.0以来引入的。

所以这里是如何使用对象和集合初始化器(请注意我使用 PascalCase代替属性而不是camelCase ):

public static void Test()
{
    UnitCategory troopsCategory = new UnitCategory
        {
            UnitCategoryName = "Troops",
            UnitType = new List<UnitType>
                {
                    new UnitType
                        {
                            UnitTypeName = "Infantry",
                            Unit = new List<Unit>
                                {
                                    new Unit
                                        {
                                            Armour = "Chitin",
                                            Attacks = "3",
                                            BallisticSkill = "100",
                                            Compsition = "20",
                                            DedicatedTransport = "No",
                                            Initiative = "3",
                                            Leadership = "5",
                                            Options = "8",
                                            SaveThrow = "6+",
                                            SpecialRules = "None",
                                            Strength = "3",
                                            T = "4",
                                            UnitName = "Hornmagant",
                                            Weapons = "Many",
                                            WeaponSkill = "3",
                                            Wounds = "1"                                               
                                        }
                                }
                        }
                }
        };

    Army army = new Army
    {
        ArmyName = "Tyranid",
        UnitCategory = new List<UnitCategory>
            {
                troopsCategory
            }
    };

    ArmyListing armyListing = new ArmyListing
    {
        Army = new List<Army>
                {
                    army
                }
    };

    armyListing.SerializeToXml(armyListing);
}

顺便说一下,using语句比手动关闭更好:

public void SerializeToXml(ArmyListing armyListing)
{
    try
    {
        var serializer = new XmlSerializer(typeof (ArmyListing));
        using (var textWriter = new StreamWriter(@"C:\Test\40k.xml"))
        {
            serializer.Serialize(textWriter, armyListing);
        }
    }
    catch (Exception ex)
    {
    }
}