How To Use TinyXML With WxWidgets

From WxWiki

Jump to: navigation, search

[edit] wxString encoding and TinyXML

TinyXml supports UTF-8 allowing to manipulate XML files in any language. TinyXml does not use or directly support wchar, TCHAR, or Microsofts _UNICODE at this time. If wxWidgets is compiled in Unicode mode, when using TinyXML we need to convert its encoding between UTF-8 and wchar/Unicode.

In ansi mode, for English users, using English XML, UTF-8 is the same as low-ASCII. You don't need to be aware of UTF-8 or change your code in any way. You can think of UTF-8 as a "superset" of ASCII.

In unicode mode, we need to convert wxString to UTF-8 encoding when using TinyXML. We could use mb_str() this wxString member function. If you want to convert a char * UTF-8 string to wxString, please use wxString Constructors with conversion to convert.

  • wxMBConvUTF8 has one predefined instance, wxConvUTF8 and could use it convert char * UTF-8 string to wxString.


TinyXML Code Example
TiXmlDocument doc;
TiXmlElement* msg;
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
doc.LinkEndChild( decl );
 
TiXmlElement * root = new TiXmlElement( "MyApp" );
doc.LinkEndChild( root );
 
wxString Name = m_textName->GetValue();
root->SetAttribute( "Name", Name.mb_str( wxConvUTF8 ) );
 
Name = _("d:/") + Name + _(".xml");
 
if(doc.SaveFile( (const char*)Name.mb_str() ))
    wxMessageBox(_("File Successfully saved\n\n")+Name);

If doc.SaveFile( (const char*)Name.mb_str() ) returns false although the path and name are correct, you might have to change all path separators from ' / ' to ' \ ' to make it work. This especially applies when wxFilename is being used for any path with TinyXML (LoadFile(..) or SaveFile(...)). In short:

Use a ' \ ' instead of ' / 'as path separator if you have troubles with loading or saving files.
Personal tools