JavaScript怎么获取XML节点的属性值

在 JavaScript 中获取 XML 节点属性值需先用 DOMParser 解析 XML 字符串为 Document 对象,再通过 querySelector 等定位目标元素,最后用 getAttribute() 或 attributes 集合读取属性,注意大小写敏感及解析异常处理。

在 JavaScript 中获取 XML 节点的属性值,核心是先解析 XML(得到 Document 对象),再定位到目标元素节点,最后用 getAttribute()attributes 集合读取属性。

1. 解析 XML 字符串得到 Document 对象

浏览器中常用 DOMParser 将 XML 字符串转为可操作的 DOM 结构:

const xmlStr = `三体`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlStr, "application/xml");

⚠️ 注意:若解析失败(如格式错误),xmlDoc 中可能出现 ,建议检查 xmlDoc.documentElement.nodeName !== "parsererror"

2. 定位目标元素节点

可用 getElementsByTagNamequerySelectordocumentElement 等方式获取节点:

  • const book = xmlDoc.querySelector("book");
  • const book = xmlDoc.getElementsByTagName("book")[0];
  • const book = xmlDoc.documentElement; // 若根元素就是 book

3. 获取属性值的两种常用方法

✅ 推荐用 getAttribute(name) —— 简洁、安全、返回字符串或 null

  • book.getAttribute("id"); // → "101"
  • book.getAttribute("lang"); // → "zh"
  • book.getAttribute("price"); // → null(不存在时)

? 或访问 attributes 集合 —— 适合遍历所有属性:

  • book.attributes["category"].value; // → "fiction"
  • book.attributes.getNamedItem("id").value; // → "101"
  • Array.from(book.attributes).forEach(attr => console.log(attr.name, attr.value));

4. 注意事项

  • XML 属性名区分大小写:getAttribute("ID")getAttribute("id")
  • HTML 模式下解析 XML 可能出错,务必指定 MIME 类型 "application/xml"
  • 若 XML 来自网络(如 fetch),注意响应类型设为 text/xml 或用 response.text() 后手动解析

基本上就这些。只要 XML 解析成功,取属性就是一步调用,不复杂但容易忽略大小写和解析异常处理。