Создание XML из многоуровневой структуры классов - PullRequest
1 голос
/ 09 февраля 2012

Я пытаюсь создать файл 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 ]

2 голосов
/ 09 февраля 2012

Посмотрите на код создания вашего объекта. Вы осваиваете все эти объекты, но никогда не связываете их вместе. В конечном итоге происходит передача полностью пустого объекта ArmyListing в сериализатор. Это правильное поведение в кодировке.

добавить

armyListing.army.Add(army)

и вы увидите, что начинаете получать какой-то вывод.

1 голос
/ 09 февраля 2012

Очень полезная функция для этой задачи: Инициализаторы объектов и коллекций , появившиеся после 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)
    {
    }
}
...