minidom中element对象无getattribute方法,正确方式是node.attributes.get("id").value;需先判断node.nodetype == node.element_node,避免对text等节点调用;namednodemap不支持下标访问,须用.get();空属性返回"",缺失属性返回none,安全写法为attr = node.attributes.get("x"); value = attr.value if attr else none。

getAttribute 方法在 minidom 中根本不存在
你写 node.getAttribute("id") 却报 AttributeError: 'Element' object has no attribute 'getAttribute'?不是你拼错了,是 xml.dom.minidom 的 Element 对象压根没这个方法 —— 这是 JavaScript DOM API 的写法,被很多人直接套用到 Python 上踩了坑。
minidom 里取属性得走标准 DOM Level 1 的路子:getAttribute() 属于 Element 在 DOM 规范里的接口,但 Python 的 minidom 实现只暴露了 getAttributeNode() 和更常用的 getAttribute() 的替代方案:直接用字典式访问或 getAttributeNode() 后取 .value。
- 正确姿势是:
node.getAttribute("id")其实能用 —— 但前提是node是xml.dom.minidom.Element实例(不是Text或Comment);很多报错是因为你误对Text节点调用了它 - 更稳妥的做法是先判断类型:
if node.nodeType == node.ELEMENT_NODE:再取属性 - 或者统一用
node.attributes.get("id"),它返回Attr对象,要取值得写node.attributes.get("id").value
node.attributes 是个 NamedNodeMap,不是 dict
你以为 node.attributes["class"] 能像字典一样取值?不行。它会抛 TypeError: unhashable type: 'Attr' 或静默失败 —— 因为 NamedNodeMap 不支持方括号键取值,只支持 .get()、.item() 和 .keys()。
-
node.attributes.get("href")返回Attr对象(可安全用于不存在的属性,不抛错) -
node.attributes.get("href").value才是你要的字符串值 -
node.attributes.item(0)按索引取第 0 个属性节点(顺序不确定,慎用于逻辑依赖) - 遍历所有属性:
for attr in node.attributes.values(): print(attr.name, attr.value)
空属性、缺失属性和默认值怎么处理
XML DTD 或 Schema 可能定义了默认属性值,但 minidom 不解析 DTD,默认值不会自动补上;空字符串属性(attr="")会被读成 "",不是 None;而完全没声明的属性,.get() 返回 None,直接调 .value 就崩。
立即学习“Python免费学习笔记(深入)”;
- 安全取值模式:
attr = node.attributes.get("data-id"); value = attr.value if attr else None - 别用
node.getAttribute("foo") or "default"—— 因为getAttribute()在属性不存在时返回空字符串"",不是None,导致默认值永远不生效 - 如果 XML 声明了 DTD 且你启用了
parser.setFeature(dom.DOMImplementation().createDocumentType(...), True),默认值才可能生效,但实际极少用,也不推荐依赖
性能与替代建议:别在循环里反复调 getAttribute
每次调 node.attributes.get("x") 都触发一次哈希查找 + 对象封装;如果在解析大 XML 的深层循环里频繁调用,叠加 GC 开销,比用 lxml 慢 3–5 倍是常态。
- 提前缓存:
attrs = {a.name: a.value for a in node.attributes.values()},后面用attrs.get("id") - 真要高频操作 XML,换
lxml.etree:elem.get("id")直接返回字符串,缺失返回None,语义清晰,速度也快 -
minidom适合小配置、教学、兼容老代码;别拿它 parse 几 MB 的日志 XML
最常被忽略的一点:getAttribute 的行为取决于节点类型,而 minidom 不强制校验节点类型 —— 你传进去的是 Text,它不会提醒你“这不是 Element”,只会默默给你抛 AttributeError。检查 node.nodeType 不是多此一举,是必选项。










