p5js中的xml文件出错(“syntaxerror:expected; but found table”)

时间:2017-12-10 10:57:24

标签: javascript xml processing p5.js

使用p5.js我正在尝试绘制12个随机颜色的方块,可以在按下鼠标时重绘 - 我用下面的代码做了:

function setup() {
//build-up canvas w/ 12 squares
createCanvas(800, 600);

for (var y=0; y<600;y+=200) {
  for (var x=0; x<800; x+=200) {
    fill(random(255), random(255), random(255));
    rect(x, y, 200, 200)
  }
}
function touchStarted() {
// figure-out where to redraw square
  var qX = (mouseX - (mouseX % 200)) / 200
  var qY = (mouseY - (mouseY % 200)) / 200

 fill(random(255), random(255), random(255));
 rect(qX*200, qY*200, 200, 200);
}

但是现在我正在尝试使用这种内容将数据保存在xml文件中:

<build>
    <square id="0" posx="0", posy="0">30</square>
    <square id="1" posx="200", posy="0">60</square>

我正试图将它作为参考高度(https://p5js.org/reference/#/p5.XML):

var xml;

function preload() {
  xml = loadXML("assets/data.xml");
}

function setup() {
  // build-up canvas w/ 12 squares
  createCanvas(800, 600);

  var children = xml.getChildren("build");

  for (var i=0; i < children.length; i++) {
    var xpos = children[i].getNum("posx");
    var ypos = children[i].getNum("posy");
    var coul = children[i].getContent();
    fill(coul);
    rect(xpos, ypos, 200, 200);
  }

但我只得到错误“SyntaxError:Expected; but found table”所以我真的迷路了......

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

试试这个: 我已将var children = xml.getChildren("build");更改为var children = xml.getChildren("square");

var xml;

function preload() {
  xml = loadXML("assets/data.xml");
}

function setup() {
  // build-up canvas w/ 12 squares
  createCanvas(800, 600);

  var children = xml.getChildren("square"); // <----- CHANGED IT FROM BUILD TO SQUARE

  for (var i=0; i < children.length; i++) {
    var xpos = children[i].getNum("posx");
    var ypos = children[i].getNum("posy");
    var coul = children[i].getContent();
    fill(coul);
    rect(xpos, ypos, 200, 200);
  }

也不要忘记关闭xml文件内部。 应该是这样的:

<build>
<square id="0" posx="0", posy="0">30</square>
<square id="1" posx="200", posy="0">60</square>
</build>