我想将数组的值添加到某个xml文件中。使用我的代码,它只需添加一个数字,并用以下数字替换它。
以下是代码:
XML xml;
int start = 1000;
int end = 1901;
int[] multiZips = new int[end- start];
for (int i = start; i < end; i++) {
multiZips[i-start] = i;
}
for (int j : multiZips ) {
String zip = str(j);
xml = loadXML("sample.xml");
XML firstChild = xml.getChild("childOne/childTwo");
firstChild.setContent(zip + ", ");
print(firstChild.getContent());
if (j < multiZips.length) {
saveXML(xml, "sample.xml");
}
}
我想在我的xml文件中保存1000到1901之间的所有数字。
提前致谢。
答案 0 :(得分:0)
您发布的代码有一些看起来有点不对劲:
XML firstChild = xml.getChild("childTwo");
if (j < multiZips.length)
。 j
从1000
升级到1900
>
而不是901
目前还不清楚您希望如何保存数据。
如果要将值与逗号连接并将其设置为节点内容,则可以执行以下操作:
XML xml;
int start = 1000;
int end = 1901;
int[] multiZips = new int[end- start];
for (int i = start; i < end; i++) {
multiZips[i-start] = i;
}
//load the XML once
xml = loadXML("sample.xml");
//get a reference to the child you want to append to
XML firstChild = xml.getChild("childTwo");
//create a string to concatenate to
String zips = "";
for (int j : multiZips ) {
String zip = str(j);
//append to string
zips += (zip + ", ");
}
//add the concatenated string
firstChild.setContent(zips);
//save once
saveXML(xml, "sample.xml");
如果您想保存单个节点,也可以这样做:
XML xml;
int start = 1000;
int end = 1901;
int[] multiZips = new int[end- start];
for (int i = start; i < end; i++) {
multiZips[i-start] = i;
}
//load once
xml = loadXML("sample.xml");
//get a reference to <childtwo>
XML firstChild = xml.getChild("childTwo");
for (int j : multiZips ) {
String zip = str(j);
//create a new node (in this case we'll call it zip, but it can be something else)
XML newNode = new XML("zip");
//set the value as it's content
newNode.setContent(zip);
//append the new node to the <childTwo> node
firstChild.addChild(newNode);
}
//save once
saveXML(xml,"sample.xml");
当你可以重复使用这个循环时,还不清楚为什么要迭代两次:for (int i = start; i < end; i++)
还要添加XML内容。