Last active
December 17, 2015 01:39
-
-
Save felton/5530029 to your computer and use it in GitHub Desktop.
Parsing XML with TinyXML2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
____ _ | |
| _ \ __ _ _ __ ___(_)_ __ __ _ | |
| |_) / _` | '__/ __| | '_ \ / _` | | |
| __/ (_| | | \__ \ | | | | (_| | | |
|_| \__,_|_| |___/_|_| |_|\__, | | |
|___/ | |
_______ _ __ ____ __ _ ____ | |
__ __/ /_ _(_)_ __ _ _\ \/ / \/ | | |___ \ | |
\ \ /\ / / / | | | | '_ \| | | |\ /| |\/| | | __) | | |
\ V V / / | | | | | | | |_| |/ \| | | | |___ / __/ | |
\_/\_/_/ |_| |_|_| |_|\__, /_/\_\_| |_|_____|_____| | |
|___/ | |
Build: g++ tinyxml2_parse.cpp tinyxml2.cpp -o tinyxml2_parse | |
(assuming you're in the tinyxml2 directory.) | |
**/ | |
#include "tinyxml2.h" | |
#include <iostream> | |
using namespace std; | |
int main(){ | |
static const char* xml = | |
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" | |
"<entries>" | |
"<entry name=\"My First Post\" age=\"52\">I believe every human has a finite number of heartbeats. I don't intend to waste any of mine</entry>" | |
"<entry name=\"The Second\" age=\"\">You know, being a test pilot isn't always the healthiest business in the world.</entry>" | |
"<entry>Entry</entry>" | |
"<entry name=\"The Third\" secretdata=\"9809832\">We have an infinite amount to learn both from nature and from each other</entry>" | |
"<entry name=\"Final Post...\" hidden=\"true\" age=\"3\">Across the sea of space, the stars are other suns.</entry>" | |
"</entries>"; | |
tinyxml2::XMLDocument doc; | |
doc.Parse(xml); | |
tinyxml2::XMLHandle docHandle(&doc); | |
tinyxml2::XMLElement *entry = docHandle.FirstChildElement("entries").ToElement(); | |
if(entry){ | |
for(tinyxml2::XMLNode *node = entry->FirstChildElement(); node; node = node->NextSibling()){ | |
tinyxml2::XMLElement *e = node->ToElement(); | |
const char *name = e->Attribute("name"); | |
if(name) cout<<name<<": "; | |
cout<<e->GetText(); | |
int true_age = e->IntAttribute("age") + 50; | |
cout<<" "<<true_age <<endl; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment