html5读取xml属性集合_获取某节点所有属性的遍历方法【指南】

12次阅读

Element.attributes 返回 Namednodemap,是 xml 节点自身属性的集合;它支持索引访问和 getNamedItem(),但非数组、不保证顺序,且不包含命名空间声明的语义解析。

html5读取xml属性集合_获取某节点所有属性的遍历方法【指南】

Element.attributes 获取 XML 节点的所有属性集合

html5 中通过 DOMParser 解析 XML 字符串后,得到的是标准的 Element 对象,其 attributes 属性返回一个 NamedNodeMap —— 这就是你要的“属性集合”。它不是数组,但可按索引访问,也支持 getNamedItem() 查找。

  • attributes 只包含该元素自身的属性,不含命名空间声明(如 xmlns)或默认属性
  • 遍历时注意:IE 以外的现代浏览器中,attributes 包含所有属性(包括 idclass 等),但不保证顺序
  • 若需兼容老版本 edge 或 IE,应改用 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,可直接用 mapFilter 处理
  • 它不返回属性节点对象,无法获取 attr.specified 或命名空间前缀信息
  • 对自定义属性(data-*)、标准属性一视同仁,无过滤逻辑
if (book.getAttributeNames) {   const names = book.getAttributeNames(); // ["id", "lang", "data-status"]   names.forEach(name => {     console.log(name, book.getAttribute(name));   }); } else {   // fallback 到 attributes.length 方式 }

XML 中 Namespace-aware 属性需要额外处理

如果你解析的是带命名空间的 XML(如 ),attributes 仍能读取到 xmlns:ns,但它的 namexmlns:nsvalue 是 URI;而 getAttributeNames() 在多数浏览器中会忽略这类声明属性。

立即学习前端免费学习笔记(深入)”;

  • 要提取命名空间绑定,必须走 attributes 遍历,并检查 attr.name.startsWith('xmlns')
  • attr.namespaceURI 对普通属性为 NULL,对命名空间声明则为 "http://www.w3.org/2000/xmlns/"
  • 不要依赖 getAttribute('xmlns:ns') —— 它在很多浏览器中返回 null,即使属性存在

属性遍历本身不难,真正容易卡住的是:没意识到 attributes 不是数组、没处理命名空间声明、或者在需要兼容时误用了 getAttributeNames()

text=ZqhQzanResources