14.2. Working with Xerces Strings

Problem

You want to be able to handle the wide-character strings used by the Xerces library safely and easily. In particular, you want to be able to store strings returned by Xerces functions as well as to convert between Xerces strings and C++ standard library strings.

Solution

You can store wide-character strings returned by Xerces library functions using the template std::basic_string specialized for the Xerces wide-character type XMLCh:

typedef std::basic_string<XMLCh> XercesString;

To translate between Xerces strings and narrow-character strings, use the overloaded static method transcode() from the class xercesc::XMLString, defined in the header xercesc/util/XMLString.hpp. Example 14-4 defines two overloaded utility functions, toNative and fromNative, that use transcode to translate from narrow-character strings to Xerces strings and vice versa. Each function has two variants, one that takes a C-style string and one that takes a C++ standard library string. These utility functions are all you’ll need to convert between Xerces string and narrow-character strings; once you define them, you’ll never need to call transcode directly.

Example 14-4. The header xerces_strings.hpp, for converting between Xerces strings and narrow-character strings

#ifndef XERCES_STRINGS_HPP_INCLUDED #define XERCES_STRINGS_HPP_INCLUDED #include <string> #include <boost/scoped_array.hpp> #include <xercesc/util/XMLString.hpp> typedef std::basic_string<XMLCh> XercesString; ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.