的XML C#XML序列化
问题描述:
我试图序列化这样一个类与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字符串。
答
这里是我做过什么来测试您的方案:
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>
希望这个帮助。
可能你会在这个问题中找到答案(http://*.com/questions/6455067/xml-serialization-question-order-of-elementsc) – 2014-11-24 16:02:58