Write a Program to Read the Content of the File Mydoc.doc' and Display It on Console
- Chief Folio
- Classes
- Files
- Related Pages
TinyXML Tutorial
What is this?
This tutorial has a few tips and suggestions on how to use TinyXML effectively.
I've also tried to include some C++ tips like how to convert strings to integers and vice versa. This isn't anything to practice with TinyXML itself, simply it may helpful for your project and then I've put it in anyway.
If you lot don't know basic C++ concepts this tutorial won't exist useful. Also if you lot don't know what a DOM is, look elsewhere start.
Earlier nosotros first
Some example XML datasets/files will exist used.
example1.xml:
<?xml version="i.0" ?> <Hello>Globe</Hello>
example2.xml:
<?xml version="i.0" ?> <poetry> <verse> Alas Swell World Alas (again) </verse> </poetry>
example3.xml:
<?xml version="i.0" ?> <shapes> <circle proper name="int-based" 10="20" y="30" r="50" /> <point name="float-based" ten="iii.v" y="52.1" /> </shapes>
example4.xml
<?xml version="1.0" ?> <MyApp> <!-- Settings for MyApp --> <Messages> <Welcome>Welcome to MyApp</Welcome> <Farewell>Thanks for using MyApp</Farewell> </Letters> <Windows> <Window name="MainFrame" x="5" y="15" w="400" h="250" /> </Windows> <Connection ip="192.168.0.i" timeout="123.456000" /> </MyApp>
Getting Started
Load XML from a file
The simplest way to load a file into a TinyXML DOM is:
TiXmlDocument md( "demo.xml" ); medico.LoadFile();
A more than real-earth usage is shown beneath. This will load the file and display the contents to STDOUT:
// load the named file and dump its construction to STDOUT void dump_to_stdout(const char* pFilename) { TiXmlDocument md(pFilename); bool loadOkay = md.LoadFile(); if (loadOkay) { printf("\n%s:\north", pFilename); dump_to_stdout( &doc ); // defined subsequently in the tutorial } else { printf("Failed to load file \"%s\"\north", pFilename); } } A simple demonstration of this role is to use a main like this:
int principal(void) { dump_to_stdout("example1.xml"); return 0; } Recollect that Example 1 XML is:
<?xml version="1.0" ?> <Hello>World</Hi>
Running the program with this XML will display this in the console/DOS window:
Certificate + Annunciation + ELEMENT Hello + TEXT[Earth]
The ``dump_to_stdout`` function is defined later in this tutorial and is useful if you want to understand recursive traversal of a DOM.
Edifice Documents Programatically
This is how to build Example one pragmatically:
void build_simple_doc( ) { // Make xml: <?xml ..><Hello>Earth</Howdy> TiXmlDocument physician; TiXmlDeclaration * decl = new TiXmlDeclaration( "i.0", "", "" ); TiXmlElement * element = new TiXmlElement( "Hello" ); TiXmlText * text = new TiXmlText( "World" ); element->LinkEndChild( text ); doc.LinkEndChild( decl ); doctor.LinkEndChild( element ); doc.SaveFile( "madeByHand.xml" ); } This can be loaded and displayed on the console with:
dump_to_stdout("madeByHand.xml"); // this func defined subsequently in the tutorial and you'll run into it is identical to Example 1:
madeByHand.xml: Document + Declaration + Element [Hello] + Text: [World]
This lawmaking produces exactly the aforementioned XML DOM but it shows a different ordering to node creation and linking:
void write_simple_doc2( ) { // same equally write_simple_doc1 just add each node // as early as possible into the tree. TiXmlDocument doc; TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "", "" ); medico.LinkEndChild( decl ); TiXmlElement * element = new TiXmlElement( "Howdy" ); doc.LinkEndChild( element ); TiXmlText * text = new TiXmlText( "Globe" ); element->LinkEndChild( text ); doc.SaveFile( "madeByHand2.xml" ); } Both of these produce the aforementioned XML, namely:
<?xml version="1.0" ?> <Hello>World</Hello>
Or in structure grade:
DOCUMENT + Declaration + ELEMENT Hello + TEXT[World]
Attributes
Given an existing node, settings attributes is easy:
window = new TiXmlElement( "Demo" ); window->SetAttribute("proper name", "Circle"); window->SetAttribute("x", v); window->SetAttribute("y", xv); window->SetDoubleAttribute("radius", iii.14159); You tin can it besides work with the TiXmlAttribute objects if you want.
The following lawmaking shows one style (not the only way) to get all attributes of an element, impress the name and string value, and if the value can exist converted to an integer or double, print that value too:
// print all attributes of pElement. // returns the number of attributes printed int dump_attribs_to_stdout(TiXmlElement* pElement, unsigned int indent) { if ( !pElement ) return 0; TiXmlAttribute* pAttrib=pElement->FirstAttribute(); int i=0; int ival; double dval; const char* pIndent=getIndent(indent); printf("\northward"); while (pAttrib) { printf( "%s%due south: value=[%s]", pIndent, pAttrib->Name(), pAttrib->Value()); if (pAttrib->QueryIntValue(&ival)==TIXML_SUCCESS) printf( " int=%d", ival); if (pAttrib->QueryDoubleValue(&dval)==TIXML_SUCCESS) printf( " d=%1.1f", dval); printf( "\n" ); i++; pAttrib=pAttrib->Next(); } render i; } Writing a document to a file
Writing a pre-built DOM to a file is trivial:
doc.SaveFile( saveFilename );
Remember, for instance, case iv:
<?xml version="1.0" ?> <MyApp> <!-- Settings for MyApp --> <Messages> <Welcome>Welcome to MyApp</Welcome> <Farewell>Cheers for using MyApp</Goodbye> </Letters> <Windows> <Window name="MainFrame" x="5" y="fifteen" w="400" h="250" /> </Windows> <Connectedness ip="192.168.0.1" timeout="123.456000" /> </MyApp>
The following function builds this DOM and writes the file "appsettings.xml":
void write_app_settings_doc( ) { TiXmlDocument dr.; TiXmlElement* msg; TiXmlDeclaration* decl = new TiXmlDeclaration( "ane.0", "", "" ); md.LinkEndChild( decl ); TiXmlElement * root = new TiXmlElement( "MyApp" ); doc.LinkEndChild( root ); TiXmlComment * annotate = new TiXmlComment(); comment->SetValue(" Settings for MyApp " ); root->LinkEndChild( comment ); TiXmlElement * msgs = new TiXmlElement( "Letters" ); root->LinkEndChild( msgs ); msg = new TiXmlElement( "Welcome" ); msg->LinkEndChild( new TiXmlText( "Welcome to MyApp" )); msgs->LinkEndChild( msg ); msg = new TiXmlElement( "Farewell" ); msg->LinkEndChild( new TiXmlText( "Cheers for using MyApp" )); msgs->LinkEndChild( msg ); TiXmlElement * windows = new TiXmlElement( "Windows" ); root->LinkEndChild( windows ); TiXmlElement * window; window = new TiXmlElement( "Window" ); windows->LinkEndChild( window ); window->SetAttribute("proper noun", "MainFrame"); window->SetAttribute("x", 5); window->SetAttribute("y", 15); window->SetAttribute("west", 400); window->SetAttribute("h", 250); TiXmlElement * cxn = new TiXmlElement( "Connection" ); root->LinkEndChild( cxn ); cxn->SetAttribute("ip", "192.168.0.ane"); cxn->SetDoubleAttribute("timeout", 123.456); // floating point attrib dump_to_stdout( &dr. ); doc.SaveFile( "appsettings.xml" ); } The dump_to_stdout part will evidence this structure:
Document + Declaration + Element [MyApp] (No attributes) + Comment: [ Settings for MyApp ] + Element [Letters] (No attributes) + Chemical element [Welcome] (No attributes) + Text: [Welcome to MyApp] + Element [Adieu] (No attributes) + Text: [Thank you for using MyApp] + Element [Windows] (No attributes) + Chemical element [Window] + name: value=[MainFrame] + 10: value=[5] int=five d=5.0 + y: value=[15] int=xv d=15.0 + w: value=[400] int=400 d=400.0 + h: value=[250] int=250 d=250.0 5 attributes + Element [Connection] + ip: value=[192.168.0.1] int=192 d=192.two + timeout: value=[123.456000] int=123 d=123.five 2 attributes
I was surprised that TinyXml, by default, writes the XML in what other APIs call a "pretty" format - it modifies the whitespace of text of elements that contain other nodes so that writing the tree includes an indication of nesting level.
I haven't looked yet to see if there is a way to turn off indenting when writing a file - its bound to exist easy.
[Lee: Information technology'due south easy in STL way, but utilize cout << myDoc. Non-STL mode is always in "pretty" format. Adding a switch would be a nice feature and has been requested.]
XML to/from C++ objects
Intro
This example assumes you're loading and saving your app settings in an XML file, eastward.g. something like example4.xml.
At that place are a number of means to do this. For example, await into the TinyBind project at http://sourceforge.net/projects/tinybind
This section shows a plain-old approach to loading and saving a basic object structure using XML.
Set up your object classes
Start off with some bones classes similar these:
#include <cord> #include <map> using namespace std; typedef std::map<std::string,std::string> MessageMap; // a basic window brainchild - demo purposes only grade WindowSettings { public: int x,y,due west,h; string name; WindowSettings() : x(0), y(0), w(100), h(100), proper noun("Untitled") { } WindowSettings(int x, int y, int westward, int h, const string& name) { this->ten=ten; this->y=y; this->westward=west; this->h=h; this->name=name; } }; grade ConnectionSettings { public: string ip; double timeout; }; class AppSettings { public: string m_name; MessageMap m_messages; list<WindowSettings> m_windows; ConnectionSettings m_connection; AppSettings() {} void salvage(const char* pFilename); void load(const char* pFilename); // but to prove how to do it void setDemoValues() { m_name="MyApp"; m_messages.clear(); m_messages["Welcome"]="Welcome to "+m_name; m_messages["Farewell"]="Thanks for using "+m_name; m_windows.clear(); m_windows.push_back(WindowSettings(fifteen,15,400,250,"Main")); m_connection.ip="Unknown"; m_connection.timeout=123.456; } }; This is a basic master() that shows how to create a default settings object tree, save information technology and load it once more:
int main(void) { AppSettings settings; settings.save("appsettings2.xml"); settings.load("appsettings2.xml"); render 0; } The following master() shows creation, modification, saving and then loading of a settings structure:
int main(void) { // block: customise and save settings { AppSettings settings; settings.m_name="HitchHikerApp"; settings.m_messages["Welcome"]="Don't Panic"; settings.m_messages["Farewell"]="Cheers for all the fish"; settings.m_windows.push_back(WindowSettings(15,25,300,250,"BookFrame")); settings.m_connection.ip="192.168.0.77"; settings.m_connection.timeout=42.0; settings.salve("appsettings2.xml"); } // cake: load settings { AppSettings settings; settings.load("appsettings2.xml"); printf("%southward: %s\northward", settings.m_name.c_str(), settings.m_messages["Welcome"].c_str()); WindowSettings & w=settings.m_windows.forepart(); printf("%s: Show window '%s' at %d,%d (%d x %d)\north", settings.m_name.c_str(), w.name.c_str(), due west.x, due west.y, w.w, w.h); printf("%due south: %due south\north", settings.m_name.c_str(), settings.m_messages["Adieu"].c_str()); } return 0; } When the save() and load() are completed (see below), running this main() displays on the console:
HitchHikerApp: Don't Panic HitchHikerApp: Show window 'BookFrame' at fifteen,25 (300 x 100) HitchHikerApp: Thank you for all the fish
Encode C++ state as XML
There are lots of different ways to approach saving this to a file. Here's i:
void AppSettings::save(const char* pFilename) { TiXmlDocument doctor; TiXmlElement* msg; TiXmlComment * annotate; string s; TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" ); doc.LinkEndChild( decl ); TiXmlElement * root = new TiXmlElement(m_name.c_str()); doc.LinkEndChild( root ); comment = new TiXmlComment(); south=" Settings for "+m_name+" "; comment->SetValue(s.c_str()); root->LinkEndChild( comment ); // cake: messages { MessageMap::iterator iter; TiXmlElement * msgs = new TiXmlElement( "Messages" ); root->LinkEndChild( msgs ); for (iter=m_messages.brainstorm(); iter != m_messages.end(); iter++) { const string & key=(*iter).first; const cord & value=(*iter).second; msg = new TiXmlElement(key.c_str()); msg->LinkEndChild( new TiXmlText(value.c_str())); msgs->LinkEndChild( msg ); } } // cake: windows { TiXmlElement * windowsNode = new TiXmlElement( "Windows" ); root->LinkEndChild( windowsNode ); list<WindowSettings>::iterator iter; for (iter=m_windows.begin(); iter != m_windows.end(); iter++) { const WindowSettings& w=*iter; TiXmlElement * window; window = new TiXmlElement( "Window" ); windowsNode->LinkEndChild( window ); window->SetAttribute("name", w.name.c_str()); window->SetAttribute("x", w.x); window->SetAttribute("y", w.y); window->SetAttribute("w", w.westward); window->SetAttribute("h", west.h); } } // cake: connectedness { TiXmlElement * cxn = new TiXmlElement( "Connexion" ); root->LinkEndChild( cxn ); cxn->SetAttribute("ip", m_connection.ip.c_str()); cxn->SetDoubleAttribute("timeout", m_connection.timeout); } doc.SaveFile(pFilename); } Running this with the modified main produces this file:
<?xml version="1.0" ?> <HitchHikerApp> <!-- Settings for HitchHikerApp --> <Messages> <Farewell>Thank you for all the fish</Farewell> <Welcome>Don't Panic</Welcome> </Letters> <Windows> <Window name="BookFrame" 10="15" y="25" w="300" h="250" /> </Windows> <Connection ip="192.168.0.77" timeout="42.000000" /> </HitchHikerApp>
Decoding state from XML
As with encoding objects, in that location are a number of approaches to decoding XML into your own C++ object structure. The post-obit approach uses TiXmlHandles.
void AppSettings::load(const char* pFilename) { TiXmlDocument doc(pFilename); if (!doc.LoadFile()) render; TiXmlHandle hDoc(&doc); TiXmlElement* pElem; TiXmlHandle hRoot(0); // block: name { pElem=hDoc.FirstChildElement().Element(); // should always have a valid root only handle gracefully if information technology does if (!pElem) render; m_name=pElem->Value(); // save this for after hRoot=TiXmlHandle(pElem); } // cake: string table { m_messages.articulate(); // trash existing table pElem=hRoot.FirstChild( "Messages" ).FirstChild().Element(); for( pElem; pElem; pElem=pElem->NextSiblingElement()) { const char *pKey=pElem->Value(); const char *pText=pElem->GetText(); if (pKey && pText) { m_messages[pKey]=pText; } } } // block: windows { m_windows.clear(); // trash existing list TiXmlElement* pWindowNode=hRoot.FirstChild( "Windows" ).FirstChild().Element(); for( pWindowNode; pWindowNode; pWindowNode=pWindowNode->NextSiblingElement()) { WindowSettings w; const char *pName=pWindowNode->Aspect("name"); if (pName) westward.name=pName; pWindowNode->QueryIntAttribute("x", &w.x); // If this fails, original value is left equally-is pWindowNode->QueryIntAttribute("y", &w.y); pWindowNode->QueryIntAttribute("w", &w.w); pWindowNode->QueryIntAttribute("hh", &w.h); m_windows.push_back(w); } } // cake: connection { pElem=hRoot.FirstChild("Connection").Element(); if (pElem) { m_connection.ip=pElem->Attribute("ip"); pElem->QueryDoubleAttribute("timeout",&m_connection.timeout); } } } Total listing for dump_to_stdout
Below is a copy-and-paste demo program for loading capricious XML files and dumping the structure to STDOUT using the recursive traversal listed above.
// tutorial demo program #include "stdafx.h" #include "tinyxml.h" // ---------------------------------------------------------------------- // STDOUT dump and indenting utility functions // ---------------------------------------------------------------------- const unsigned int NUM_INDENTS_PER_SPACE=2; const char * getIndent( unsigned int numIndents ) { static const char * pINDENT=" + "; static const unsigned int LENGTH=strlen( pINDENT ); unsigned int n=numIndents*NUM_INDENTS_PER_SPACE; if ( n > LENGTH ) n = LENGTH; render &pINDENT[ LENGTH-north ]; } // same every bit getIndent merely no "+" at the end const char * getIndentAlt( unsigned int numIndents ) { static const char * pINDENT=" "; static const unsigned int LENGTH=strlen( pINDENT ); unsigned int n=numIndents*NUM_INDENTS_PER_SPACE; if ( due north > LENGTH ) northward = LENGTH; render &pINDENT[ LENGTH-due north ]; } int dump_attribs_to_stdout(TiXmlElement* pElement, unsigned int indent) { if ( !pElement ) return 0; TiXmlAttribute* pAttrib=pElement->FirstAttribute(); int i=0; int ival; double dval; const char* pIndent=getIndent(indent); printf("\n"); while (pAttrib) { printf( "%southward%southward: value=[%south]", pIndent, pAttrib->Name(), pAttrib->Value()); if (pAttrib->QueryIntValue(&ival)==TIXML_SUCCESS) printf( " int=%d", ival); if (pAttrib->QueryDoubleValue(&dval)==TIXML_SUCCESS) printf( " d=%1.1f", dval); printf( "\n" ); i++; pAttrib=pAttrib->Next(); } render i; } void dump_to_stdout( TiXmlNode* pParent, unsigned int indent = 0 ) { if ( !pParent ) return; TiXmlNode* pChild; TiXmlText* pText; int t = pParent->Type(); printf( "%due south", getIndent(indent)); int num; switch ( t ) { example TiXmlNode::DOCUMENT: printf( "Document" ); break; case TiXmlNode::Element: printf( "Element [%south]", pParent->Value() ); num=dump_attribs_to_stdout(pParent->ToElement(), indent+one); switch(num) { case 0: printf( " (No attributes)"); break; instance 1: printf( "%s1 attribute", getIndentAlt(indent)); break; default: printf( "%due south%d attributes", getIndentAlt(indent), num); break; } interruption; case TiXmlNode::Comment: printf( "Comment: [%s]", pParent->Value()); break; case TiXmlNode::UNKNOWN: printf( "Unknown" ); break; case TiXmlNode::TEXT: pText = pParent->ToText(); printf( "Text: [%s]", pText->Value() ); break; example TiXmlNode::DECLARATION: printf( "Declaration" ); break; default: break; } printf( "\due north" ); for ( pChild = pParent->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) { dump_to_stdout( pChild, indent+one ); } } // load the named file and dump its construction to STDOUT void dump_to_stdout(const char* pFilename) { TiXmlDocument doc(pFilename); bool loadOkay = md.LoadFile(); if (loadOkay) { printf("\n%south:\due north", pFilename); dump_to_stdout( &dr. ); // defined later in the tutorial } else { printf("Failed to load file \"%due south\"\northward", pFilename); } } // ---------------------------------------------------------------------- // primary() for printing files named on the control line // ---------------------------------------------------------------------- int master(int argc, char* argv[]) { for (int i=1; i<argc; i++) { dump_to_stdout(argv[i]); } return 0; } Run this from the command line or a DOS window, e.chiliad.:
C:\dev\tinyxml> Debug\tinyxml_1.exe example1.xml example1.xml: Document + Announcement + Element [Hullo] (No attributes) + Text: [World]
Authors and Changes
- Written past Ellers, Apr, May, June 2005
- Modest edits and integration into doc system, Lee Thomason September 2005
- Updated past Ellers, October 2005
Generated on Sat Mar twenty 21:xvi:54 2010 for TinyXml by
Source: http://www.grinninglizard.com/tinyxmldocs/tutorial0.html
Post a Comment for "Write a Program to Read the Content of the File Mydoc.doc' and Display It on Console"