anna anna
anna anna

Reputation: 13

How to add Content to XML with Proceesing

I would like to add the values of an array to a certain xml File. With my code it just add one number and replaces it with the following number.

Here is the code:

  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");
    }
  }

I would like to save all numbers between 1000 and 1901 in my xml File.

Thanks in advance.

Upvotes: 1

Views: 56

Answers (1)

George Profenza
George Profenza

Reputation: 51837

There are a few things that look a bit off with the code you posted:

  1. You're loading and saving the same xml file multiple times while attempting to load the same node.
  2. You're trying to access a node by something that looks like an xpath, although I don't think Processing's XML library supports that. However you can get the nested node by it's name: XML firstChild = xml.getChild("childTwo");
  3. You have a condition that is never met: if (j < multiZips.length). j goes from 1000 to 1900 which is > than 901

It's unclear how you want to save the data.

If you want to concatenate the values with commas and set that as a node content you can do something like this:

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");

If you want to save individual nodes you can do that too:

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");

It's also unclear why you iterate twice, when you could re-use this loop: for (int i = start; i < end; i++) to also add XML content.

Upvotes: 1

Related Questions