2013-03-08 2 views
-3

Я отлаживал его до сих пор, список имеет значения .. однако его не записывает их в файл.XML: Запись в файл имеет значение NULL?

Я не уверен, почему это null.

Класс GameObjects содержит все поля.

GameObjectData только для списка.

Затем ChestPlate наследует от GameObjects. Причина в том, что я делаю игру, и все значения в GameObjects относятся к ChestPlate.

код ниже:

[Serializable] 
public class GameObjects 
{ 
    //Defines name within XML file: 
    [XmlElement("Item_ID")] 
    public int Item_ID { get; set; } 
    [XmlElement("Item_Name")] 
    public string Item_Name = "bob"; 
    [XmlElement("Item_type")] 
    public string Item_type = "GameObject"; 
    [XmlElement("Item_Level")] 
    public int Item_Level = 5; 
    [XmlElement("Item_description")] 
    public string Item_description = "best description evar"; 

    public GameObjects(int id, string name, string type, int level, string description) 
    { 
     this.Item_ID = id; 
     this.Item_Name = name; 
     this.Item_type = type; 
     this.Item_Level = level; 
     this.Item_description = description; 
    } 
} 

[Serializable] 
[XmlInclude(typeof(GameObjects))] 
public class GameObjectData 
{ 
    [XmlArrayItem(typeof(GameObjects))] 
    public List<GameObjects> GameList { get; set;} 
} 

public class ChestPlate : GameObjects 
{ 
    [XmlElement("Armour_Rating")] 
    int Armour_Rating = 5; 

    public ChestPlate(int Armour_id, string Armour_name, string Armour_type, int Armour_level, string Armour_description) 
     : base(Armour_id, Armour_name, Armour_type, Armour_level, Armour_description) 
    { 
     this.Item_ID = Armour_id; 
     this.Item_Name = Armour_name; 
     this.Item_type = Armour_type; 
     this.Item_Level = Armour_level; 
     this.Item_description = Armour_description;  
    } 

    public void SerializeToXML(List<GameObjects> responsedata) 
    {   
     GameObjectData f = new GameObjectData(); 
     f.GameList = new List<GameObjects>(); 
     f.GameList.Add(new GameObjects { Item_ID = 1234, Item_Name = "OMG", Item_type = "CHESTPLATE", Item_Level = 5, Item_description = "omg" }); 

     XmlSerializer serializer = new XmlSerializer(typeof(GameObjectData)); 
     TextWriter textWriter = new StreamWriter(@"C:\Test.xml"); 

     serializer.Serialize(textWriter, f); 

     Console.WriteLine(f);   
    } 

class Program 
{ 
    static void Main(string[] args) 
    { 
     GameObjects a = new GameObjects(); 
     ChestPlate b = new ChestPlate(); 
     List<GameObjects> d = new List<GameObjects>(); 
     b.SerializeToXML(d); 
     Console.ReadLine(); 
    } 
} 
+0

Что такое нуль при отладке? – jrummell

+0

в разделе "serializer" – callum

ответ

1

Я запустить свой код и он, кажется, сериализовать ваши данные правильно тестовый файл создал остроумие h - параметры по умолчанию, заданные базовым классом.

Что меня беспокоит, это реализация. Я уверен, что у вас есть больше работы, но вам нужно правильно распоряжаться объектами, обеспечить атрибут и сериализацию унаследованных классов, а родители - правильно, иначе вы не будете способный де-сериализовать правильно и т. д. Я бы посоветовал вам взглянуть в Интернете на лучшие практики для сериализации XML в .net, есть множество примеров онлайн, но, пожалуйста, просмотрите несколько приведенных ниже.

что-то еще может быть хорошо, чтобы проверить, если вам действительно нужно использовать XML является JSON достаточно хорошо или даже бинарной сериализации.

Существует несколько записей в вики сообщества в stackoverflow и в том числе вопросы о лучших практиках.

Пожалуйста, под выводом кода, который вы указали вместе с полным исходным кодом ниже. Обратите внимание, что я изменил местоположение, в котором вы сохраняете файл xml, на «. \ Test.xml», как правило, в папке с папкой и папке отладки, в приложении не будет проблем с написанием тоже подобных разрешений и т. Д.

Также обратите внимание, что на xml ниже вы потеряли тот факт, что вы сериализовали объект ChestPlate.

<?xml version="1.0" encoding="utf-8"?> 
<GameObjectData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <GameList> 
    <GameObjects> 
     <Item_Name>OMG</Item_Name> 
     <Item_type>CHESTPLATE</Item_type> 
     <Item_Level>5</Item_Level> 
     <Item_description>omg</Item_description> 
     <Item_ID>1234</Item_ID> 
    </GameObjects> 
    </GameList> 
</GameObjectData> 

Code база используется для генерации XML

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Xml.Serialization; 

namespace ConsoleApplication12 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      GameObjects a = new GameObjects(); 
      ChestPlate b = new ChestPlate(); 
      List<GameObjects> d = new List<GameObjects>(); 
      b.SerializeToXML(d); 
      Console.ReadLine(); 
     } 

    } 

    [Serializable] 
    public class GameObjects 
    { 
     //Defines name within XML file: 
     [XmlElement("Item_ID")] 
     public int Item_ID { get; set; } 
     [XmlElement("Item_Name")] 
     public string Item_Name = "bob"; 
     [XmlElement("Item_type")] 
     public string Item_type = "GameObject"; 
     [XmlElement("Item_Level")] 
     public int Item_Level = 5; 
     [XmlElement("Item_description")] 
     public string Item_description = "best description evar"; 

     public GameObjects(int id, string name, string type, int level, string description) 
     { 
      this.Item_ID = id; 
      this.Item_Name = name; 
      this.Item_type = type; 
      this.Item_Level = level; 
      this.Item_description = description; 
     } 

     public GameObjects() 
     { 

     } 

    } 

    [Serializable] 
    [XmlInclude(typeof(GameObjects))] 
    public class GameObjectData 
    { 
     [XmlArrayItem(typeof(GameObjects))] 
     public List<GameObjects> GameList { get; set; } 


    } 

    public class ChestPlate : GameObjects 
    { 
     [XmlElement("Armour_Rating")] 
     int Armour_Rating = 5; 

     public ChestPlate(int Armour_id, string Armour_name, string Armour_type, int Armour_level, string Armour_description) 
      : base(Armour_id, Armour_name, Armour_type, Armour_level, Armour_description) 
     { 
      this.Item_ID = Armour_id; 
      this.Item_Name = Armour_name; 
      this.Item_type = Armour_type; 
      this.Item_Level = Armour_level; 
      this.Item_description = Armour_description; 
     } 

     public ChestPlate() 
     { 


     } 


     public void SerializeToXML(List<GameObjects> responsedata) 
     { 
      GameObjectData f = new GameObjectData(); 
      f.GameList = new List<GameObjects>(); 
      f.GameList.Add(new GameObjects { Item_ID = 1234, Item_Name = "OMG", Item_type = "CHESTPLATE", Item_Level = 5, Item_description = "omg" }); 


      XmlSerializer serializer = new XmlSerializer(typeof(GameObjectData)); 
      TextWriter textWriter = new StreamWriter(@".\Test.xml"); 

      serializer.Serialize(textWriter, f); 

      Console.WriteLine(f); 
     } 
    } 
}