在javascript中解析xml数据主要有两种方法:1. 使用domparser解析xml字符串,通过new domparser()创建解析器并调用parsefromstring方法将xml字符串转换为dom文档,随后使用dom api如getelementsbytagname或getelementsbytagnamens(处理命名空间)提取数据;2. 使用xmlhttprequest获取远程xml文件,在onload事件中通过xhr.responsexml获取解析后的dom文档,并检查其有效性以确保解析成功;对于格式错误的xml,可通过检测parsererror元素判断解析是否失败;domparser适用于本地小数据量解析,性能较高,而xmlhttprequest适合从服务器异步加载xml数据,避免阻塞主线程,处理大型文件时可结合流式解析器优化内存使用。

在 JavaScript 中解析 XML 数据,主要涉及将 XML 字符串转换为可操作的 JavaScript 对象,这样你就可以方便地提取和使用 XML 数据中的信息。通常,你会使用
DOMParser
XMLHttpRequest
解决方案:
JavaScript 解析 XML 的方法主要有两种:使用
DOMParser
XMLHttpRequest
DOMParser
DOMParser
const xmlString = `<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J.K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "application/xml");
// 现在你可以使用 DOM API 来访问 XML 数据
const books = xmlDoc.getElementsByTagName("book");
for (let i = 0; i < books.length; i++) {
const title = books[i].getElementsByTagName("title")[0].textContent;
const author = books[i].getElementsByTagName("author")[0].textContent;
console.log(`Title: ${title}, Author: ${author}`);
}这里,我们首先创建了一个 XML 字符串。然后,我们实例化
DOMParser
parseFromString
"application/xml"
getElementsByTagName
XMLHttpRequest
如果你的 XML 数据存储在服务器上,你需要使用
XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open("GET", "books.xml", true); // 假设你的 XML 文件名为 books.xml
xhr.onload = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const xmlDoc = xhr.responseXML; // 获取 XML 文档对象
// 检查是否成功解析 XML
if (xmlDoc) {
const books = xmlDoc.getElementsByTagName("book");
for (let i = 0; i < books.length; i++) {
const title = books[i].getElementsByTagName("title")[0].textContent;
const author = books[i].getElementsByTagName("author")[0].textContent;
console.log(`Title: ${title}, Author: ${author}`);
}
} else {
console.error("Failed to parse XML.");
}
} else {
console.error("Failed to load XML.");
}
};
xhr.onerror = function() {
console.error("Network error occurred.");
};
xhr.send();这个例子中,我们创建了一个
XMLHttpRequest
open
onload
xhr.responseXML
responseXML
null
XML 命名空间用于避免元素名称冲突。如果你的 XML 文档使用了命名空间,你需要使用
getElementsByTagNameNS
getElementsByTagName
const xmlStringWithNS = `<root xmlns:bk="http://example.com/books">
<bk:book>
<bk:title>My Book</bk:title>
</bk:book>
</root>`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlStringWithNS, "application/xml");
const books = xmlDoc.getElementsByTagNameNS("http://example.com/books", "book");
if (books.length > 0) {
const title = books[0].getElementsByTagNameNS("http://example.com/books", "title")[0].textContent;
console.log(`Title: ${title}`);
}在这个例子中,我们使用了
getElementsByTagNameNS
XML 解析可能会因为 XML 格式不正确而失败。
DOMParser
parseError
const xmlString = `<bookstore>
<book>
<title>Invalid XML - Missing closing tag</title>
</book>`; // 缺少 </bookstore> 闭合标签
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "application/xml");
const errorNode = xmlDoc.querySelector("parsererror");
if (errorNode) {
console.error("XML Parsing Error:", errorNode.textContent);
} else {
const books = xmlDoc.getElementsByTagName("book");
// ... 正常处理 XML
}这个例子中,我们检查了
parsererror
parsererror
通常来说,
DOMParser
XMLHttpRequest
xml-stream
以上就是js 如何解析XML数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号