C#读取XML节点属性值 XmlNode.Attributes使用方法

1次阅读

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

C#读取XML节点属性值 XmlNode.Attributes使用方法

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 场景必须用 GetAttributeNodeGetNamedItem

属性值里有空格、换行或实体编码怎么处理

XmlAttribute.ValueGetAttribute() 返回的都是已解码后的字符串,XML 解析器自动处理了 &&< 等,但不会 trim 空格或折叠空白。

  • XML 规范允许属性值前后保留空白," hello " 就是原样返回,需要手动 .Trim()
  • 换行符在属性值中极少出现,但如果 DTD 允许且 XML 中写了 attr="line1 line2"Value 会包含 n
  • 不要对属性值再调用 HttpUtility.HtmlDecode 或类似函数——XML 解析器已做完全部转义还原

属性名大小写、命名空间、节点类型、空值防御,这四点漏掉任何一个,Attributes 就容易返回意外结果。

text=ZqhQzanResources