

新闻资讯
技术学院Element.attributes 返回 NamedNodeMap,是 XML 节点自身属性的集合;它支持索引访问和 getNamedItem(),但非数组、不保证顺序,且不包含命名空间声明的语义解析。
Element.attributes 获取 XML 节点的所有属性集合HTML5 中通过 DOMParser 解析 XML 字符串后,得到的是标准的 Element 对象,其 attributes 属性返回一个 NamedNodeMap —— 这就是你要的“属性集合”。它不是数组,但可按索引访问,也支持 getNamedItem() 查找。
attributes 只包含该元素自身的属性,不含命名空间声明(如 xmlns)或默认属性attributes 包含所有属性(包括 id、class 等),但不保证顺序getAttributeNames()(仅支持现代浏览器)或手动遍历 attributes.length
attributes 的两种可靠写法推荐使用传统索引遍历,兼容性最好;for...of 在部分环境(如某些 Electron 内核)中对 NamedNodeMap 支持不稳定。
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(' ', 'application/xml');
const book = xmlDoc.querySelector('book');
// ✅ 推荐:用 length + 索引遍历
for (let i = 0; i < book.attributes.length; i++) {
const attr = book.attributes[i];
console.log(attr.name, attr.value); // "id" "123", "lang" "zh", "data-status" "draft"
}
// ⚠️ 注意:以下写法在 Safari 15.6 之前或旧版 Chromium 中可能报错
// for (const attr of book.attributes) { ... }
getAttributeNames() 更简洁但有兼容限制如果只关心属性名列表(比如做白名单校验),getAttributeNames() 返回字符串数组,语义清晰、写法干净,但不支持 IE 和 Safari ≤14.1。
Array,可直接用 map、filter 处理attr.specified 或命名空间前缀信息data-*)、标准属性一视同仁,无过滤逻辑if (book.getAttributeNames) {
const names = book.get
AttributeNames(); // ["id", "lang", "data-status"]
names.forEach(name => {
console.log(name, book.getAttribute(name));
});
} else {
// fallback 到 attributes.length 方式
}
如果你解析的是带命名空间的 XML(如 ),attributes 仍能读取到 xmlns:ns,但它的 name 是 xmlns:ns,value 是 URI;而 getAttributeNames() 在多数浏览器中会忽略这类声明属性。
attributes 遍历,并检查 attr.name.startsWith('xmlns')
attr.namespaceURI 对普通属性为 null,对命名空间声明则为 "http://www.w3.org/2000/xmlns/"
getAttribute('xmlns:ns') —— 它在很多浏览器中返回 null,即使属性存在attributes 不是数组、没处理命名空间声明、或者在需要兼容时误用了 getAttributeNames()。