C#XmlSerializer使用各种方式设置属性的对象

时间:2018-10-17 06:55:01

标签: c# xmlserializer

我有这样的类定义

public class ScenarioModel {
    public string Version { get; set; }
}

我想将此类的实例序列化为2种不同格式的XML文件。
(使用System.Xml.Serialization.XmlSerializer

文件1:

<?xml version="1.0" encoding="utf-8"?>
<Scenario>
    <Version>1.0.0</Vesion>
</Scenario>

文件2:

<?xml version="1.0" encoding="utf-8"?>
<Scenario version="1.0.0">
</Scenario>

如何为ScenarioModel类定义进行设置。

1 个答案:

答案 0 :(得分:2)

型号:

[XmlRoot("Scenario")]
public class ScenarioModel
{
    public string Version { get; set; }
}

Program.cs:

static void Main(string[] args)
{
    ScenarioModel model = new ScenarioModel { Version = "1.0.0" };

    XmlSerializer ser = null;
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add(string.Empty, string.Empty);

    Console.WriteLine("File 1\n==================");
    ser = new XmlSerializer(model.GetType());
    ser.Serialize(Console.Out, model, ns);

    Console.WriteLine("\n\nFile 2\n==================");
    XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
    XmlAttributes attr = new XmlAttributes { XmlAttribute = new XmlAttributeAttribute("Version") };
    attrOverrides.Add(model.GetType(), "Version", attr);
    ser = new XmlSerializer(model.GetType(), attrOverrides);
    ser.Serialize(Console.Out, model, ns);

    Console.WriteLine();
    Console.ReadLine();
}

应该给您类似的东西

File 1
==================
<?xml version="1.0" encoding="utf-8"?>
<Scenario>
  <Version>1.0.0</Version>
</Scenario>

File 2
==================
<?xml version="1.0" encoding="utf-8"?>
<Scenario Version="1.0.0" />