p5.js | loadXML()函数
loadXML()函数用于读取文件或 URL 的内容并将其作为 XML 对象返回。该文件必须存在于要访问的草图目录中。此方法可用于支持最大 64MB 的文件大小。
该函数是异步的,因此建议在 preload()函数中调用,以确保该函数在其他函数之前执行。
句法:
loadXML(filename, callback, errorCallback )
参数:此函数接受三个参数,如上所述,如下所述:
- 文件名:这是一个字符串,表示必须从中加载 XML 数据的文件路径或 URL。
- 回调:这是一个函数,当该函数执行成功时调用。此函数的第一个参数是从文件加载的 XML 数据。它是一个可选参数。
- errorCallback:这是一个函数,如果执行该函数有任何错误,则调用该函数。此函数的第一个参数是错误响应。它是一个可选参数。
以下示例说明了 p5.js 中的 loadXML ()函数:
示例 1:
/* == Contents of books.xml ==
The Adventures of Sherlock Holmes: Part One
Arthur Conan Doyle
323
Detective fiction
*/
let loadedXML = null;
function setup() {
createCanvas(500, 200);
textSize(22);
text("Click on the button below to "
+ "load XML from file", 20, 20);
// Create a button for loading the XML
loadBtn = createButton("Load XML from file");
loadBtn.position(30, 50)
loadBtn.mousePressed(loadXMLFile);
}
function loadXMLFile() {
// Load the XML from file
loadedXML = loadXML('books.xml', onFileload);
}
function onFileload() {
text("XML loaded successfully...", 30, 100);
let book = loadedXML.getChildren();
// Get the content of the tags
let name = book[0].getContent();
let author = book[1].getContent();
let price = book[2].getContent();
let genre = book[3].getContent();
text("Name: " + name, 30, 140);
text("Author: " + author, 30, 160);
text("Price: " + price, 30, 180);
text("Genre: " + genre, 30, 200);
}
输出:
示例 2:
/* == Contents of movies.xml ==
The Godfather
The Wizard of Oz
Citizen Kane
*/
let loadedXML = null;
function setup() {
createCanvas(500, 450);
textSize(22);
text("Click on the button below to "
+ "load XML from file", 20, 20);
// Create a button for loading the XML
loadBtn = createButton("Load XML from file");
loadBtn.position(30, 50)
loadBtn.mousePressed(loadXMLFile);
}
function loadXMLFile() {
// Load the XML from file
loadedXML = loadXML('movies.xml', onFileload);
}
function onFileload() {
// Get the children with the "movie" tag
let children = loadedXML.getChildren('movie');
for (let i = 0; i < children.length; i++) {
// Get the content of the tag
let name = children[i].getContent();
// Get a numerical attribute
let year = children[i].getNum('year');
// Get a string attribute
let director = children[i].getString('director');
text("Name: " + name, 30, 100 + i * 80);
text("Year: " + year, 30, 120 + i * 80);
text("Director: " + director, 30, 140 + i * 80);
}
}
输出:
在线编辑器: https://editor.p5js.org/
环境设置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
参考: https://p5js.org/reference/#/p5/loadXML