我有以下课程:
[Serializable] public class SomeModel { [XmlElement("SomeStringElementName")] public string SomeString { get; set; } [XmlElement("SomeInfoElementName")] public int SomeInfo { get; set; } }
(当填充一些测试数据时)并使用XmlSerializer.Serialize()进行序列化会生成以下XML:
<SomeModel> <SomeStringElementName>testData</SomeStringElementName> <SomeInfoElementName>5</SomeInfoElementName> </SomeModel>
我需要拥有的是:
<SomeModel> <SomeStringElementName Value="testData" /> <SomeInfoElementName Value="5" /> </SomeModel>
有没有办法在不编写自己的自定义序列化代码的情况下将其指定为属性?
您将需要包装器类:
public class SomeIntInfo { [XmlAttribute] public int Value { get; set; } } public class SomeStringInfo { [XmlAttribute] public string Value { get; set; } } public class SomeModel { [XmlElement("SomeStringElementName")] public SomeStringInfo SomeString { get; set; } [XmlElement("SomeInfoElementName")] public SomeIntInfo SomeInfo { get; set; } }
或更通用的方法,如果您喜欢:
public class SomeInfo<T> { [XmlAttribute] public T Value { get; set; } } public class SomeModel { [XmlElement("SomeStringElementName")] public SomeInfo<string> SomeString { get; set; } [XmlElement("SomeInfoElementName")] public SomeInfo<int> SomeInfo { get; set; } }
然后:
class Program { static void Main() { var model = new SomeModel { SomeString = new SomeInfo<string> { Value = "testData" }, SomeInfo = new SomeInfo<int> { Value = 5 } }; var serializer = new XmlSerializer(model.GetType()); serializer.Serialize(Console.Out, model); } }
将产生:
<?xml version="1.0" encoding="ibm850"?> <SomeModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SomeStringElementName Value="testData" /> <SomeInfoElementName Value="5" /> </SomeModel>