【问题标题】:Xml Element Position in C# XML SerializationC# XML 序列化中的 XML 元素位置
【发布时间】:2014-11-24 15:36:01
【问题描述】:

我正在尝试使用 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 文档的最后添加 Insurance 属性:

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

我需要这样做,因为处理 xml 的服务器只能在此布局中正常工作(而且我无法更改服务器代码)。 我尝试将属性移动到类的末尾,但这没有任何区别,而且我没有找到任何与序列化相关的属性会有所帮助。 我可以通过将 xml 操作为字符串来解决这个问题,但我更喜欢更优雅的解决方案。对象有很多属性,所以我不想手动创建 xml 字符串。

【问题讨论】:

  • 也许你会在这个question找到答案

标签: c# .net xml serialization xmlserializer


【解决方案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>

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 2016-04-13
    相关资源
    最近更新 更多