xmlnode.attributes 返回 null 是因节点无属性,需先检查 node.nodetype == xmlnodetype.element 且 node.attributes != null;优先用 ((xmlelement)node).getattribute("name") 避免空引用,注意命名空间和大小写。

XmlNode.Attributes 返回 null 怎么办
直接访问 XmlNode.Attributes 得到 null,不是 bug,是节点没属性——比如 <item>abc</item> 这种纯文本节点,Attributes 就是 null,不是空集合。
- 先用
node.Attributes != null && node.Attributes.Count > 0做空检查,别直接 .Count 或遍历 -
XmlElement类型才保证Attributes非 null;如果原始是XmlNode,建议先as XmlElement转换再取 - 读取前确认节点类型:
node.NodeType == XmlNodeType.Element,否则像XmlNodeType.Text节点根本不会有属性
取不到指定属性值,Attribute.Name 对不上
XML 属性名区分大小写,而且可能带命名空间前缀(如 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"),XmlAttribute.Name 返回的是带前缀的完整名,不是本地名。
- 用
node.Attributes["id"]比遍历Attributes更安全,但注意:只匹配无命名空间的属性;有前缀得用node.Attributes["xsi:type"] - 要忽略命名空间查属性,用
node.Attributes.GetNamedItem("type", "http://www.w3.org/2001/XMLSchema-instance") - 调试时打印所有属性:
foreach (XmlAttribute a in node.Attributes) { Console.WriteLine($"[{a.Name}] = {a.Value}"); },看清实际键名
用 GetAttribute("xxx") 还是 Attributes["xxx"]
两者行为不同:GetAttribute() 是 XmlElement 方法,查不到返回空字符串;Attributes["xxx"] 是索引器,查不到返回 null —— 容易引发 NullReferenceException。
- 优先用
((XmlElement)node).GetAttribute("id"),省去 null 判断,语义也更清晰 - 如果 node 确实是
XmlElement类型(比如用SelectSingleNode("//item")得到的),直接调用GetAttribute即可 -
GetAttribute不支持命名空间解析,要 namespace-aware 场景必须用GetAttributeNode或GetNamedItem
属性值里有空格、换行或实体编码怎么处理
XmlAttribute.Value 和 GetAttribute() 返回的都是已解码后的字符串,XML 解析器自动处理了 & → &、< → 等,但不会 trim 空格或折叠空白。
- XML 规范允许属性值前后保留空白,
" hello "就是原样返回,需要手动.Trim() - 换行符在属性值中极少出现,但如果 DTD 允许且 XML 中写了
attr="line1 line2",Value会包含\n - 不要对属性值再调用
HttpUtility.HtmlDecode或类似函数——XML 解析器已做完全部转义还原
Attributes 就容易返回意外结果。










