HTML5读取XML属性与遍历方法
时间:2026-01-23
浏览:350
作者:佚名
小伙伴们对文章编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《HTML5读取XML属性集合及遍历方法详解》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!
Element.attributes 返回 NamedNodeMap,是 XML 节点自身属性的集合;它支持索引访问和 getNamedItem(),但非数组、不保证顺序,且不包含命名空间声明的语义解析。

用 Element.attributes 获取 XML 节点的所有属性集合
HTML5 中通过 DOMParser 解析 XML 字符串后,得到的是标准的 Element 对象,其 attributes 属性返回一个 NamedNodeMap —— 这就是你要的“属性集合”。它不是数组,但可按索引访问,也支持 getNamedItem() 查找。
attributes只包含该元素自身的属性,不含命名空间声明(如xmlns)或默认属性- 遍历时注意:IE 以外的现代浏览器中,
attributes包含所有属性(包括id、class等),但不保证顺序 - 若需兼容老版本 Edge 或 IE,应改用
getAttributeNames()(仅支持现代浏览器)或手动遍历attributes.length
遍历 attributes 的两种可靠写法
推荐使用传统索引遍历,兼容性最好;for...of 在部分环境(如某些 Electron 内核)中对 NamedNodeMap 支持不稳定。
const parser = new DOMParser();
const xmlDoc = parser.parseFromString('<book id="123" lang="zh" data-status="draft"></book>', '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<string>,可直接用map、filter处理 - 它不返回属性节点对象,无法获取
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(如 <ns:book xmlns:ns="http://example.com">),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()。理论要掌握,实操不能落!以上关于《HTML5读取XML属性与遍历方法》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
