贝利信息

JS如何获取XML标签的属性

日期:2025-12-24 00:00 / 作者:煙雲
在 JavaScript 中获取 XML 标签属性需先用 DOMParser 解析 XML 字符串为 Document 对象,再通过 getAttribute() 等 DOM 方法读取属性值,并注意 MIME 类型、错误检查及命名空间支持。

在 JavaScript 中获取 XML 标签的属性,核心是先解析 XML 字符串为 DOM 对象(如 Document),再通过标准 DOM 方法访问元素及其属性。

解析 XML 字符串为文档对象

浏览器原生支持 DOMParser,它是处理 XML 字符串最可靠的方式:

定位目标元素并读取属性

拿到 Document 后,用类似 HTML 的 DOM 方法查找元素,再调用 getAttribute() 或访attributes 集合:

完整示例:读取 gory="fiction">

const xmlStr = `
  The Wind
`;

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
}

注意事项

XML 属性名区分大小写,且不自动标准化命名(比如 XML:langxml:lang 是不同属性);如果 XML 带命名空间,需用 getAttributeNS() 并传入对应 URI;另外,IE8 及更早版本不支持 DOMParser,需用 ActiveXObject("Microsoft.XMLDOM") 回退(现代项目通常无需兼容)。