首先通过fetch API获取XML字符串,再用DOMParser解析为DOM对象,接着使用getElementsByTagName、getAttribute等DOM方法遍历、修改、添加或删除节点,最后用XMLSerializer将更新后的DOM序列化回字符串,实现完整XML数据操作流程。

在JavaScript中操作XML数据,核心在于利用浏览器内置的DOM解析器(
DOMParser
要深入理解如何在JavaScript里玩转XML,我们得从几个关键步骤说起。
首先,你得有个XML数据源。这通常意味着从服务器异步加载。过去我们用
XMLHttpRequest
fetch
获取XML数据:
立即学习“Java免费学习笔记(深入)”;
使用
fetch
fetch('data.xml') // 假设你的XML文件名为 data.xml
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.text(); // 获取原始XML字符串
})
.then(xmlString => {
// 接下来就是解析这个字符串了
console.log("获取到的XML字符串:", xmlString);
parseAndManipulateXML(xmlString);
})
.catch(error => {
console.error('获取XML数据时出错:', error);
});解析和操作XML字符串:
一旦你拿到了XML字符串,就需要把它变成JavaScript能理解和操作的DOM对象。
DOMParser
// 假设我们有一个XML字符串示例
const sampleXml = `
<catalog>
<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>
</catalog>
`;
function parseAndManipulateXML(xmlString) {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "application/xml");
// 检查解析错误
const errorNode = xmlDoc.querySelector('parsererror');
if (errorNode) {
console.error('XML解析错误:', errorNode.textContent);
return;
}
console.log("解析后的XML DOM对象:", xmlDoc);
// 现在你可以像操作HTML DOM一样操作这个xmlDoc了
// 1. 获取元素:
// 比如,获取所有book元素
const books = xmlDoc.getElementsByTagName("book");
console.log("找到的书籍数量:", books.length);
// 遍历并打印书名和作者
for (let i = 0; i < books.length; i++) {
const titleElement = books[i].getElementsByTagName("title")[0];
const authorElement = books[i].getElementsByTagName("author")[0];
if (titleElement && authorElement) {
console.log(`书名: ${titleElement.textContent}, 作者: ${authorElement.textContent}`);
}
// 2. 获取属性:
const category = books[i].getAttribute("category");
if (category) {
console.log(` 分类: ${category}`);
}
}
// 3. 修改元素内容和属性:
if (books.length > 0) {
const firstBookTitle = books[0].getElementsByTagName("title")[0];
if (firstBookTitle) {
firstBookTitle.textContent = "JavaScript Mastery Guide (Updated)"; // 修改文本内容
console.log("第一本书名已更新:", firstBookTitle.textContent);
}
books[0].setAttribute("category", "programming"); // 修改属性
console.log("第一本书的分类已更新为:", books[0].getAttribute("category"));
}
// 4. 创建并添加新元素:
const newBook = xmlDoc.createElement("book");
newBook.setAttribute("category", "tech");
const newTitle = xmlDoc.createElement("title");
newTitle.textContent = "Web Development with AI";
const newAuthor = xmlDoc.createElement("author");
newAuthor.textContent = "AI Co-pilot";
const newYear = xmlDoc.createElement("year");
newYear.textContent = "2024";
newBook.appendChild(newTitle);
newBook.appendChild(newAuthor);
newBook.appendChild(newYear);
xmlDoc.documentElement.appendChild(newBook); // 添加到根元素 (catalog) 下
console.log("已添加新书。");
// 5. 删除元素:
if (books.length > 1) {
const secondBook = books[1]; // 注意这里books是live collection,删除后长度会变
xmlDoc.documentElement.removeChild(secondBook);
console.log("已删除第二本书。");
}
// 6. 将修改后的DOM对象序列化回XML字符串:
const serializer = new XMLSerializer();
const updatedXmlString = serializer.serializeToString(xmlDoc);
console.log("修改后的XML字符串:\n", updatedXmlString);
}
// 调用解析函数,演示操作
// parseAndManipulateXML(sample以上就是怎么使用JavaScript操作XML数据?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号