#include <tinyxml2.h>
using namespace tinyxml2;
Followed by that we will define a string with a very simple XML document. It will contain a root element and a nested element with an integer value.char * testDocument = "<root><element>7</element></root>";
Moving on to the Arduino 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. This object will expose to us the methods we need to parse the document.XMLDocument xmlDocument;
To parse the content, we simply need to call the Parse method on the XMLDocument, passing as input the string with the document.if(xmlDocument.Parse(testDocument)!= XML_SUCCESS){
Serial.println("Error parsing");
return;
};
XMLNode * root = xmlDocument.FirstChild();
XMLElement * element = root->FirstChildElement("element");
Finally, to obtain the value of the element, we can use the QueryIntText method of our XMLElement. This method receives as input a pointer to an integer, where the value will be stored.int val;
element->QueryIntText(&val);
After we obtain the value, we will print it to the serial port.Serial.println(val);
The final complete code can be seen below.#include <tinyxml2.h>
using namespace tinyxml2;
char * testDocument = "<root><element>7</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");
int val;
element->QueryIntText(&val);
Serial.println(val);
}
void loop() {}