在JavaScript中遍历XML有多种方法,常见的包括使用DOMParser解析XML字符串,然后使用DOM方法进行遍历,以及使用XMLHttpRequest或Fetch API获取XML数据后进行解析。以下是一些基础概念和示例代码:
getElementsByTagName
、querySelectorAll
等,用于遍历和操作XML文档。// XML字符串
const xmlString = `
<library>
<book id="1">
<title>JavaScript: The Good Parts</title>
<author>Douglas Crockford</author>
</book>
<book id="2">
<title>Eloquent JavaScript</title>
<author>Marijn Haverbeke</author>
</book>
</library>
`;
// 解析XML字符串
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "application/xml");
// 遍历book元素
const books = xmlDoc.getElementsByTagName("book");
for (let i = 0; i < books.length; i++) {
const book = books[i];
const id = book.getAttribute("id");
const title = book.getElementsByTagName("title")[0].childNodes[0].nodeValue;
const author = book.getElementsByTagName("author")[0].childNodes[0].nodeValue;
console.log(`Book ID: ${id}, Title: ${title}, Author: ${author}`);
}
// 假设有一个返回XML数据的URL
const url = "https://example.com/library.xml";
fetch(url)
.then(response => response.text())
.then(str => (new window.DOMParser()).parseFromString(str, "application/xml"))
.then(xmlDoc => {
const books = xmlDoc.getElementsByTagName("book");
for (let i = 0; i < books.length; i++) {
const book = books[i];
const id = book.getAttribute("id");
const title = book.getElementsByTagName("title")[0].childNodes[0].nodeValue;
const author = book.getElementsByTagName("author")[0].childNodes[0].nodeValue;
console.log(`Book ID: ${id}, Title: ${title}, Author: ${author}`);
}
})
.catch(error => console.error('Error fetching XML:', error));
DOMParser
会抛出解析错误。可以使用xmlDoc.getElementsByTagName("parsererror")
来检查是否有解析错误。DOMParser
会抛出解析错误。可以使用xmlDoc.getElementsByTagName("parsererror")
来检查是否有解析错误。sax-js
库),它是一种事件驱动的解析器,性能更好。希望这些信息对你有所帮助!如果有更多具体问题,欢迎继续提问。
领取专属 10元无门槛券
手把手带您无忧上云