Small demo of TinyXml. TinyXml is a compact library that implements XML Parsing and Manipulation.
main.cpp
- Committer:
- wvd_vegt
- Date:
- 2022-01-18
- Revision:
- 1:54c50324309d
- Parent:
- 0:091ca51848a0
File content as of revision 1:54c50324309d:
#include "mbed.h"
#include "tinyxml.h"
#include <string>
//See http://www.grinninglizard.com/tinyxml/ for more information on how to use tinyxml.
//See TINYXML Library for license.
//
//TODO Document library and app in embed style.
DigitalOut myled(LED1);
int main() {
//Setup Tx, Rx.
Serial usb(USBTX, USBRX);
usb.baud(115200);
// Create the local filesystem under the name "local".
// DO NOT FORGET THIS CALL OR SAVING WON'T WORK!
LocalFileSystem local("local");
// Create some Xml to experiment on.
const char* demoStart =
"<?xml version=\"1.0\" standalone='no' >\r\n"
"<!-- Our to do list data -->\r\n"
"<ToDo>\r\n"
"<!-- Do I need a secure PDA? -->\r\n"
"<Item priority=\"1\" distance='close'> Go to the <bold>Toy store!</bold></Item>\r\n"
"<Item priority=\"2\" distance='none'> Do bills </Item>\r\n"
"<Item priority=\"2\" distance='far & back'> Look for Evil Dinosaurs! </Item>\r\n"
"</ToDo>\r\n";
// Load Xml into a XmlDocument.
TiXmlDocument doc("/local/demotest.xml");
// Parse Xml.
doc.Parse(demoStart);
// Get the tagname of the Root Element (ToDo).
// Note: doc.RootElement()->Value().c_str() is not compatible with printf! E153
string tag = doc.RootElement()->Value();
usb.printf("RootElement = <%s>\r\n\r\n", tag.c_str());
// Iterate Elements with for loop.
usb.printf("Enumerating Item Child Tags:\r\n");
for (TiXmlNode* child = doc.RootElement()->FirstChild(); child; child = child->NextSibling() ) {
if (child->Type()==TiXmlNode::TINYXML_ELEMENT) {
tag = child->Value();
usb.printf(" Child = <%s>\r\n", tag.c_str());
usb.printf(" Text = '%s'\r\n\r\n", child->ToElement()->GetText());
}
}
//Walk Elements by FirstChildElement/NextSiblingElement.
usb.printf("Walking Item Child Tags:\r\n");
TiXmlElement* child = doc.RootElement()->FirstChildElement("Item");
do {
tag = child->Value();
usb.printf(" Child = <%s>\r\n", tag.c_str());
usb.printf(" Text = '%s'\r\n\r\n", child->ToElement()->GetText());
child = child->NextSiblingElement("Item");
} while (child);
//Save to a file on the /local/ filesystem on Usb.
usb.printf("Saving with filename:\r\n");
doc.SaveFile("/local/out_1.xml");
//Save to a file on the /local/ filesystem on Usb.
usb.printf("Saving with FILE:\r\n");
FILE *fp = fopen("/local/out_2.xml", "w");
doc.SaveFile(fp);
fclose(fp);
if ( doc.Error() ) {
usb.printf( "Error in %s: %s\n", doc.Value(), doc.ErrorDesc() );
exit( 1 );
}
//Print the Parsed Xml.
usb.printf("Printing XML:\r\n");
TiXmlPrinter printer;
printer.SetLineBreak("\r\n"); //Default is "\n".
doc.Accept(&printer);
usb.printf("%s\r\n", printer.CStr());
while (1) {
//Wait...
}
}