C# System.Xml.Serialization反序列化textList返回null问题
问题原因
textList反序列化结果始终为null的核心问题有两处:
Text类下的textChoiceList属性仅定义了get访问器,缺少公共set访问器。System.Xml.Serialization的反序列化逻辑要求所有待映射的属性必须具备公共set访问器,否则序列化器无法为该属性赋值,会直接跳过对应节点的解析流程,最终导致下层的textList节点完全没有被读取。- 实体类的根节点标记不匹配:你在
PointCode类上添加了[XmlRoot]特性,但提供的XML片段最外层根节点是<Code>,<PointCode>只是它的子节点,如果直接以PointCode为根执行反序列化,外层节点匹配失败也会影响解析结果。 - 额外注意:非根层级的嵌套类不需要添加
[XmlRoot]特性,该特性仅用于标记反序列化的最顶层节点,嵌套元素只需要通过属性上的[XmlElement]/[XmlAttribute]指定映射名称即可,多余的[XmlRoot]标记会干扰节点匹配逻辑。
修复后可用的实体类代码
// 如果从XML最外层<Code>节点开始反序列化,用这个类作为根 [XmlRoot("Code")] public class CodeRoot { [XmlAttribute("codeName")] public string CodeName { get; set; } [XmlAttribute("codeDesc")] public string CodeDesc { get; set; } [XmlAttribute("codeType")] public string CodeType { get; set; } [XmlElement("PointCode")] public PointCode PointCode { get; set; } } // 如果直接从<PointCode>节点开始反序列化,可保留该类上的[XmlRoot]特性 [XmlRoot("PointCode")] public class PointCode { [XmlAttribute("codeLinework")] public string codeLinework { get; set; } [XmlElement("CodeAttributes")] public List<CodeAttributes> codeAttributes { get; set; } } public class CodeAttributes { [XmlAttribute("attributeName")] public string attributeName { get; set; } [XmlAttribute("attributeType")] public string attributeType { get; set; } [XmlAttribute("valueType")] public string valueType { get; set; } [XmlAttribute("valueRegion")] public string valueRegion { get; set; } [XmlElement("text")] public Text text { get; set; } // 匹配XML中出现的<integer />空节点,避免未识别节点抛出异常 [XmlElement("integer")] public object IntegerNode { get; set; } } public class Text { // 核心修复:添加公共set访问器 [XmlElement("textChoiceList")] public TextChoiceList textChoiceList { get; set; } } public class TextChoiceList { [XmlElement("textList")] public List<TextList> textList { get; set; } } public class TextList { [XmlAttribute("textListValue")] public string textListValue { get; set; } }
验证结果
使用上述实体类反序列化你提供的XML片段,可以正常读取到两个textList节点的属性值,分别为Square Kerb和Roll Kerb,不会再出现null的情况。
内容的提问来源于stack exchange,提问作者SteveJ71
相关产品推荐
相关产品推荐

