#include <tinyxml2.h>
using namespace tinyxml2;
char * testDocument = "<root><element att=\"10\">test</element></root>";
Moving on to the Arduino setup, we will start by opening a serial connection, so we are able to output results from our program.Serial.begin(115200);
Then we will declare an object of class XMLDocument and perform the parsing of our document.if(xmlDocument.Parse(testDocument)!= XML_SUCCESS){
Serial.println("Error parsing");
return;
};
If the parsing is successful, we will proceed to obtain the root node of the document. We can do that with a call to the FirstChild method on our XMLDocument.XMLNode * root = xmlDocument.FirstChild();
Next we will obtain the child element of the root node, since it is the one that contains the attribute we want to obtain. This is done with a call to the FirstChildElement method on our root node, passing as input the name of the element we want to obtain.XMLElement * element = root->FirstChildElement("element");
To obtain our attribute, we need to call the QueryIntAttribute method on our element. Note that we can use this method since our attribute is a number, which means the conversion of the attribute to an integer is possible.int attribute; if(element->QueryIntAttribute("att", &attribute) != XML_SUCCESS){ Serial.println("Could not obtain the attribute"); return; };
Serial.println(attribute);
The final code can be seen below.#include <tinyxml2.h>
using namespace tinyxml2;
char * testDocument = "<root><element att=\"10\">test</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 attribute;
if(element->QueryIntAttribute("att", &attribute) != XML_SUCCESS){
Serial.println("Could not obtain the attribute");
return;
};
Serial.println(attribute);
}
void loop() {}