2016-09-15 152 views
0

我的對象結構與下面的簡化代碼類似。請注意,國家和汽車都需要成爲班級,由於代碼未包含在示例中,因此我無法使用字符串列表/數組。我想XML序列化,然後反序列化對象。XML包含對象列表的對象的序列化列表

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Xml.Serialization; 

namespace XMLapp 
{ 
    public partial class Form1 : Form 
    { 
     List<Countries> Country = new List<Countries>(); 
     List<string> cars = new List<string>(); 

     public Form1() 
     { 
      InitializeComponent(); 

      cars.Add("Audi"); 
      cars.Add("BMW"); 
      cars.Add("Mercedes"); 
      addCountry("Germany", cars); 

      cars.Clear(); 
      cars.Add("Ford"); 
      cars.Add("Chevrolet"); 
      cars.Add("Jeep"); 
      addCountry("USA", cars); 

      TestXmlSerialize(); 
      Console.WriteLine("Generated list"); 
     } 

     void TestXmlSerialize() 
     { 
      XmlSerializer x = new XmlSerializer(Country.GetType()); 
      x.Serialize(Console.Out, Country); 
     } 

     void addCountry(string name, List<string> cars) 
     { 
      Countries newCountry = new Countries(); 
      newCountry.Name = name; 
      newCountry.AddCar(cars); 
      Country.Add(newCountry); 
     } 
    } 

    public class Countries 
    { 
     public string Name { get; set; } 
     List<Cars> car = new List<Cars>(); 

     public void AddCar(List<string> cars) 
     { 
      for (int i = 0; i < cars.Count; i++) 
      { 
       Cars newCar = new Cars(); 
       newCar.brand = cars[i]; 
       car.Add(newCar); 
      } 
     } 

     class Cars 
     { 
      public string brand; 
     } 

    } 
} 

這會產生以下輸出:

<?xml version="1.0" encoding="IBM437"?> 
<ArrayOfCountries xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Countries> 
    <Name>Germany</Name> 
    </Countries> 
    <Countries> 
    <Name>USA</Name> 
    </Countries> 
</ArrayOfCountries> 

不過,我希望沿着

線的東西,我可以看到的是,汽車品牌都妥善保存在當地人&汽車窗口,但是如何將它們包含在序列化中?

回答

1

XmlSerializer只序列化公共字段和屬性。你需要讓'汽車'領域和'汽車'級公開。

它不會生成您在問題中發佈的精確xml佈局,但它可以讓您序列化和反序列化對象。

+0

哦,沒錯!謝謝你,解決了它。 – Caliber