在 JavaScript 中获取 XML 标签属性需先用 DOMParser 解析 XML 字符串为 Document 对象,再通过 getAttribute() 等 DOM 方法读取属性值,并注意 MIME 类型、错误检查及命名空间支持。
在 JavaScript 中获取 XML 标签的属性,核心是先解析 XML 字符串为 DOM 对象(如 Document),再通过标准 DOM 方法访问元素及其属性。
浏览器原生支持 DOMParser,它是处理 XML 字符串最可靠的方式:
new DO
MParser().parseFromString(xmlStr, "text/xml") 得到一个 Document 对象"text/xml"(不是 "application/xml" 或其他,否则某些浏览器可能不按 XML 解析)document.querySelector("parsererror") 判断是否出错)拿到 Document 后,用类似 HTML 的 DOM 方法查找元素,再调用 getAttribute() 或访问 attributes 集合:
element.getAttribute("name") —— 最常用,直接返回指定属性值(不存在则返回 null)element.hasAttribute("name") —— 先判断是否存在该属性,避免未定义行为element.attributes —— 返回 NamedNodeMap,可遍历所有属性:for (let attr of element.attributes) { console.log(attr.name, attr.value); }
const xmlStr = ``; const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlStr, "text/xml"); // 检查解析错误 if (xmlDoc.querySelector("parsererror")) { console.error("XML 解析失败"); } const book = xmlDoc.querySelector("book"); if (book) { console.log(book.getAttribute("id")); // "101" console.log(book.getAttribute("category")); // "fiction" console.log(book.hasAttribute("lang")); // false } The Wind
XML 属性名区分大小写,且不自动标准化命名(比如 XML:lang 和 xml:lang 是不同属性);如果 XML 带命名空间,需用 getAttributeNS() 并传入对应 URI;另外,IE8 及更早版本不支持 DOMParser,需用 ActiveXObject("Microsoft.XMLDOM") 回退(现代项目通常无需兼容)。