2014-11-24 125 views
0

我試圖序列化這樣一個類與XmlSerializer類的XML元素的位置:的XML C#XML序列化

public class Car { 
    public InsuranceData Insurance { get; set; } // InsuranceData is a class with many properties 
    public int Person Owner { get; set; } 
    public int Age { get; set; } 
    public string Model { get; set; } 

    // lots of other properties... 
} 

我想有保險財產在的盡頭XML文檔:

<Car> 
    ... 
    <Insurance> 
    ... 
    </Insurance> 
</Car> 

我需要這樣做,因爲處理XML服務器僅在此佈局正常工作,(我不能更改服務器的代碼)。 我試着將屬性移動到類的最後,但它沒有什麼區別,我還沒有找到任何與序列化相關的屬性,這將有所幫助。 我可以通過操作xml作爲字符串來解決這個問題,但我更喜歡更優雅的解決方案。這些對象有很多屬性,所以我不想手動創建xml字符串。

+2

可能你會在這個問題中找到答案(http://stackoverflow.com/questions/6455067/xml-serialization-question-order-of-elementsc) – 2014-11-24 16:02:58

回答

1

這裏是我做過什麼來測試您的方案:

 public static void Main(string[] args) 
 
     { 
 
      Insurance i = new Insurance(); 
 
      i.company = "State Farm"; 
 

 
      Car c = new Car(); 
 
      c.model = "Mustang"; 
 
      c.year = "2014"; 
 
      c.ins = i; 
 

 
      XmlSerializer xs = new XmlSerializer(typeof(Car)); 
 
      StreamWriter sw = new StreamWriter("Car.xml"); 
 
      xs.Serialize(sw, c); 
 
      sw.Close(); 
 
     } 
 

 
     public class Car 
 
     { 
 
      public string model { get; set; } 
 
      public string year { get; set; } 
 
      public Insurance ins {get; set;} 
 
     } 
 

 
     public class Insurance 
 
     { 
 
      public string company { get; set; } 
 
     }

...這是我的結果:

<?xml version="1.0" encoding="utf-8"?> 
 
<Car xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
 
    <model>Mustang</model> 
 
    <year>2014</year> 
 
    <ins> 
 
    <company>State Farm</company> 
 
    </ins> 
 
</Car>

希望這個幫助。