Data Input 349
18.8 Using the Processing XML Library
e functionality of the simpleML library, though easy to use, is quite limited. If you want to create your
own XML documents, or parse multiple elements of a document with a custom algorithm, you are out of
luck. For more sophisticated XML functionality, there are two options. e fi rst, more advanced option is
proXML ( http://www.texone.org/proxml/ ) created by Christian Riekoff . While the learning curve is a bit
steeper, you have direct access to the XML tree structure and can read and write XML documents.
e second option, which we will explore in this chapter, is Processing ’s built-in XML library.
import processing.xml.*;
Once the library is imported, the fi rst step is to create an XMLElement object. is object will load the
data from XML documents (stored locally or on the web). e constructor requires two arguments, “ this ”
and the fi lename or URL path for the XML document.
String url = " xmldocument.xml";
XMLElement xml = new XMLElement(this,url);
Unlike simpleML, this XML library pauses the sketch and waits for the document to load. For an
asynchronous approach to XML parsing, you will need to use proXML.
An XMLElement object represents one element of an XML tree. When a document is fi rst loaded, that
element object is always the root element. simpleML did the work of traversing the tree and fi nding the
right information for us. With the Processing XML library, we have to do this work ourselves. Although
this is more complex, we have more control over how we search and what we search for.
Referring back to Figure 18.13 , we can fi nd the temperature via the following path:
1. e root element of the tree is “ RSS. ”
2. “ RSS ” has a child element named “ Channel. ”
3. e 13th child of “ Channel ” is “ item. ” ( e diagram is simplifi ed to show only one child of channel.)
4. e sixth child of “ item ” is “ yweather:condition. ”
5. e temperature is stored in “ yweather:condition ” as the attribute “ temp. ”
e children of an element are accessed with an index (starting at zero, same as an array) passed into the
getChild( ) function. e content of an element is retrieved with getContent( ) and attributes are read as
either numbers— getIntAttribute( ), getFloatAttribute( ) —or text— getStringAttribute( ) .
// Accessing the first child element of the root element
XMLElement channel = xml.getChild(0);
Following steps 1 through 5 outlined above through the XML tree, we have:
XMLElement xml = new XMLElement(this, url);
XMLElement channel = xml.getChild(0);
XMLElement item = channel.getChild(12);
XMLElement condition = item.getChild(5);
temp = condition.getIntAttribute( "temp");
The 13th child of an element is index #12.