2013-03-15 54 views
0

我有2類,定義如下:XML節點是空的,而反序列化過程

[Serializable()] 
public class Topology 
{ 
    [XmlElement("floors")] 
    public Floor[] Floors { get; set; } 
} 

[Serializable()] 
public class Floor 
{ 
    [XmlElement("name")] 
    public string name { get; set; } 

    [XmlElement("map_path")] 
    public string map_path { get; set; } 
} 

欲反序列化如下所示的XML文件,並我使用下面指定的方法進行反序列化XML文件。

XMLFILE

<?xml version="1.0" encoding="iso-8859-9"?> 
<Topology> 
    <floors> 
     <floor id="1"> 
      <name>1</name> 
      <map_path>C:\</map_path> 
     </floor> 
      <floor id="2"> 
      <name>2</name> 
      <map_path>D:\</map_path> 
     </floor> 
    </floors> 
</Topology> 

Deserialize方法

 static void Main(string[] args) 
     { 
      XmlSerializer serializer = new XmlSerializer(typeof(Topology)); 

      StreamReader reader = new StreamReader(@"C:\topology2.xml"); 
      Topology top = (Topology)serializer.Deserialize(reader); 
      reader.Close(); 

      for (int i = 0; i < top.Floors.Length; i++) 
       Console.WriteLine(top.Floors[i].name + top.Floors[i].map_path); 

      Console.ReadLine(); 
     } 

我可以得到 「地板」,但我無法得到的名稱和map_path節點值。我該怎麼辦?

回答

1

您的XML文件不適合xml序列化程序讀取。請按照以下格式進行操作:

<?xml version="1.0" encoding="iso-8859-9"?> 
<Topology> 
    <floors id="1"> 
     <name>1</name> 
     <map_path>C:\</map_path> 
    </floors> 
    <floors id="2"> 
     <name>1</name> 
     <map_path>C:\</map_path> 
    </floors> 
</Topology>