在 javascript 中获取 xml 标签属性需先用 domparser 解析 xml 字符串为 document 对象,再通过 getattribute() 等 dom 方法读取属性值,并注意 mime 类型、错误检查及命名空间支持。

在 JavaScript 中获取 XML 标签的属性,核心是先解析 XML 字符串为 DOM 对象(如 Document),再通过标准 DOM 方法访问元素及其属性。
解析 XML 字符串为文档对象
浏览器原生支持 DOMParser,它是处理 XML 字符串最可靠的方式:
- 使用
new DOMParser().parseFromString(xmlStr, "text/xml")得到一个Document对象 - 注意 MIME 类型必须是
"text/xml"(不是"application/xml"或其他,否则某些浏览器可能不按 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); }
完整示例:读取 gory="fiction">
const xmlStr = `<library>
<book id="101" category="fiction"><title>The Wind</title></book>
</library>`;
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:lang 和 xml:lang 是不同属性);如果 XML 带命名空间,需用 getAttributeNS() 并传入对应 URI;另外,IE8 及更早版本不支持 DOMParser,需用 ActiveXObject("Microsoft.XMLDOM") 回退(现代项目通常无需兼容)。










