TinyXML-2
2.1.0
|
(The XML is an excerpt from "dream.xml").
int example_3() { static const char* xml = "<?xml version=\"1.0\"?>" "<!DOCTYPE PLAY SYSTEM \"play.dtd\">" "<PLAY>" "<TITLE>A Midsummer Night's Dream</TITLE>" "</PLAY>";
The structure of the XML file is:
For this example, we want to print out the title of the play. The text of the title (what we want) is child of the "TITLE" element which is a child of the "PLAY" element.
We want to skip the declaration and dtd, so the method FirstChildElement() is a good choice. The FirstChildElement() of the Document is the "PLAY" Element, the FirstChildElement() of the "PLAY" Element is the "TITLE" Element.
XMLDocument doc; doc.Parse( xml ); XMLElement* titleElement = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" );
We can then use the convenience function GetText() to get the title of the play.
const char* title = titleElement->GetText(); printf( "Name of play (1): %s\n", title );
Text is just another Node in the XML DOM. And in fact you should be a little cautious with it, as text nodes can contain elements.
Consider: A Midsummer Night's <b>Dream</b>
It is more correct to actually query the Text Node if in doubt:
XMLText* textNode = titleElement->FirstChild()->ToText();
title = textNode->Value();
printf( "Name of play (2): %s\n", title );
Noting that here we use FirstChild() since we are looking for XMLText, not an element, and ToText() is a cast from a Node to a XMLText.