您描述的映射不是XmlSerializer 支持的映射。如果没有以下之一,您将无法以这种方式序列化 Employee:
- 实施
IXmlSerializable - 我确实不推荐;很容易把它弄得一团糟,尤其是反序列化代码
- 通过
XDocument 或XmlDocument 手动完成(同样,工作量很大)
- 创建一个可从
XmlSerializer 使用且与您的架构匹配的 DTO 模型
坦率地说,我会使用最后一个选项,这可能意味着创建类似的东西(完全未经测试,但我会在一分钟内尝试):
[XmlRoot("Test")]
public class DtoRoot {
[XmlArray("Testdata")]
[XmlArrayItem("abc")]
public List<KeyValuePair> Items {get;} = new List<KeyValuePair>();
public string this[string key] => Items.FirstOrDefault(x => x.Key == key)?.Value;
}
public class KeyValuePair{
[XmlAttribute("name")]
public string Key {get;set;}
[XmlText]
public string Value {get;set;}
}
并使用类似的东西:
Employee emp = new Employee
{
FirstName = "Fred",
LastName = "Flintstone"
};
var obj = new DtoRoot {
Items = {
new KeyValuePair { Key = "fname", Value = emp.FirstName },
new KeyValuePair { Key = "lname", Value = emp.LastName},
} };
var ser = new XmlSerializer(typeof(DtoRoot));
ser.Serialize(Console.Out, obj);
这给了我们(忽略encoding - 那是因为Console.Out):
<?xml version="1.0" encoding="ibm850"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Testdata>
<abc name="fname">Fred</abc>
<abc name="lname">Flintstone</abc>
</Testdata>
</Test>
要反序列化:反序列化为DtoRoot 实例,然后使用索引器:
var obj = (DtoRoot)ser.Deserialize(source);
var emp = new Employee {
FirstName = obj["fname"],
LastName = obj["lname"],
};