簡體   English   中英

C#XML序列化中的Xml元素位置

[英]Xml Element Position in C# XML Serialization

我正在嘗試使用XmlSerializer類將這樣的類序列化為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字符串。

這是我為測試您的方案所做的:

  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> 

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM