#include <tinyxml2.h>
using namespace tinyxml2;
char * testDocument = "<root><element>7</element><element>4</element><element>10</element></root>";
Moving on to the setup function, we will start by opening a serial connection, so we can output the results of our program.Serial.begin(115200);
Then we will declare an object of class XMLDocument, which will allow us to parse the XML document.XMLDocument xmlDocument;
To perform the actual parsing, we simply need to call the parse method on the previous object, passing as input the string with the XML document.XMLDocument xmlDocument;
if(xmlDocument.Parse(testDocument)!= XML_SUCCESS){
Serial.println("Error parsing");
return;
}
XMLNode * root = xmlDocument.FirstChild();
Now that we have the root node, we will obtain its first child element with a call to the FirstChildElement method. As input, we will pass a string with the name of the element that we want to look for.Note that the previous call will return the first element named “element“. Nonetheless, since we have a list of them, we will iterate through this list on a loop.XMLElement * element = root->FirstChildElement(
"element"
);
while(element != NULL){
// loop implementation
}
Before we analyze how to navigate through the elements, we will first print the value of the current element.int val;
element->QueryIntText(&val);
Serial.println(val);
Then, to obtain the next element, we simply need to call the NextSiblingElement method on the current element.while(element != NULL){
int val;
element->QueryIntText(&val);
Serial.println(val);
element = element->NextSiblingElement("element");
}
The final code can be seen below.#include <tinyxml2.h>
using namespace tinyxml2;
char * testDocument = "<root><element>7</element><element>4</element><element>10</element></root>";
void setup() {
Serial.begin(115200);
XMLDocument xmlDocument;
if(xmlDocument.Parse(testDocument)!= XML_SUCCESS){
Serial.println("Error parsing");
return;
}
XMLNode * root = xmlDocument.FirstChild();
XMLElement * element = root->FirstChildElement("element");
while(element != NULL){
int val;
element->QueryIntText(&val);
Serial.println(val);
element = element->NextSiblingElement("element");
}
}
void loop() {}