如何为现有C#类成员通过代码添加XmlAttribute实现XML反序列化
问题修正方案
你的问题出在XmlAttributeAttribute的初始化参数错误,以及XmlAttributeOverrides的配置细节上,以下是修正后的完整实现:
错误点分析
- 你创建
XmlAttributeAttribute时传入了字符串"XmlAttribute",这会让序列化器尝试匹配XML中名为XmlAttribute的属性,而非目标的my_record_id。 - 需确保
MyClass中的my_record_id是公共字段/属性,XmlSerializer仅处理公共成员。
修正后的代码
1. 正确配置XmlAttributeOverrides
// 配置XML属性映射 XmlAttributes wbAttributes = new XmlAttributes(); // 直接指定XML中的属性名,若属性名与成员名一致,可省略参数直接new XmlAttributeAttribute() wbAttributes.XmlAttribute = new XmlAttributeAttribute("my_record_id"); XmlRootAttribute xroot = new XmlRootAttribute("MyClass"); XmlAttributeOverrides xOver = new XmlAttributeOverrides(); // 关联类类型、成员名和配置的特性 xOver.Add(typeof(MyClass), "my_record_id", wbAttributes);
2. 反序列化方法(优化资源释放)
static T DeserializeXML<T>(string xml, XmlAttributeOverrides overrides, XmlRootAttribute root) { var serializer = new XmlSerializer(typeof(T), overrides, null, root, ""); using (var reader = XmlReader.Create(new StringReader(xml))) { return (T)serializer.Deserialize(reader); } }
3. 调用代码
// 示例XML字符串,实际从文件读取 string xmlString = "<MyClass my_record_id=\"1\" otherfield=\"othervalue\" />"; MyClass c = DeserializeXML<MyClass>(xmlString, xOver, xroot); // 此时c.my_record_id会被正确赋值为1
批量处理多个成员
如果需要为多个字段添加XML属性映射,重复执行xOver.Add即可:
// 为otherfield也配置XML属性映射 XmlAttributes otherAttrs = new XmlAttributes(); otherAttrs.XmlAttribute = new XmlAttributeAttribute("otherfield"); xOver.Add(typeof(MyClass), "otherfield", otherAttrs);
内容的提问来源于stack exchange,提问作者David W
相关产品推荐
相关产品推荐

