RapidXML是C++中可用的解析XML的库之一。要获取值,我们可以使用类似以下的代码:
node->first_node("xmlnode")->value()
这个命令返回char*数据类型。有没有办法以Unicode的形式读取值,这样我就可以将其赋值到WCHAR或wstring变量中?
RapidXML是C++中可用的解析XML的库之一。要获取值,我们可以使用类似以下的代码:
node->first_node("xmlnode")->value()
在这里,您需要将字符串转换为宽字符字符串。您可以使用标准库std来完成。
#include <string>
#include <codecvt>
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::string strSample; // convert str to wstr
std::wstring wstrValue = converter.from_bytes(strSample);
std::wstring wstrSample; // convert wstr to str
std::string strValue = converter.to_bytes(wstrSample);
RapidXml是字符类型不可知的,可以使用窄字符和宽字符。当前版本不完全支持UTF-16或UTF-32,因此对宽字符的使用有些无能为力。但是,如果数据的字节序与机器的字节序匹配,它应该可以成功解析包含UTF-16或UTF-32的wchar_t字符串。
所以我只需要使用以下内容:
#include <rapidxml/rapidxml.hpp>
typedef rapidxml::xml_node<wchar_t> const * xml_node_cptr;
typedef rapidxml::xml_node<wchar_t> * xml_node_ptr;
typedef rapidxml::xml_attribute<wchar_t> const * xml_attribute_cptr;
typedef rapidxml::xml_attribute<wchar_t> * xml_attribute_ptr;
typedef rapidxml::xml_document<wchar_t> xml_doc;
node->first_node(L"xmlnode")->value()
CStringW ConvertUTF8ToUTF16( __in const CHAR * pszTextUTF8 )
{
//
// Special case of NULL or empty input string
//
if ( (pszTextUTF8 == NULL) || (*pszTextUTF8 == '\0') )
{
// Return empty string
return L"";
}
//
// Consider CHAR's count corresponding to total input string length,
// including end-of-string (\0) character
//
const size_t cchUTF8Max = INT_MAX - 1;
size_t cchUTF8;
HRESULT hr = ::StringCchLengthA( pszTextUTF8, cchUTF8Max, &cchUTF8 );
if ( FAILED( hr ) )
{
AtlThrow( hr );
}
// Consider also terminating \0
++cchUTF8;
// Convert to 'int' for use with MultiByteToWideChar API
int cbUTF8 = static_cast<int>( cchUTF8 );
//
// Get size of destination UTF-16 buffer, in WCHAR's
//
int cchUTF16 = ::MultiByteToWideChar(
CP_UTF8, // convert from UTF-8
MB_ERR_INVALID_CHARS, // error on invalid chars
pszTextUTF8, // source UTF-8 string
cbUTF8, // total length of source UTF-8 string,
// in CHAR's (= bytes), including end-of-string \0
NULL, // unused - no conversion done in this step
0 // request size of destination buffer, in WCHAR's
);
ATLASSERT( cchUTF16 != 0 );
if ( cchUTF16 == 0 )
{
AtlThrowLastWin32();
}
//
// Allocate destination buffer to store UTF-16 string
//
CStringW strUTF16;
WCHAR * pszUTF16 = strUTF16.GetBuffer( cchUTF16 );
//
// Do the conversion from UTF-8 to UTF-16
//
int result = ::MultiByteToWideChar(
CP_UTF8, // convert from UTF-8
MB_ERR_INVALID_CHARS, // error on invalid chars
pszTextUTF8, // source UTF-8 string
cbUTF8, // total length of source UTF-8 string,
// in CHAR's (= bytes), including end-of-string \0
pszUTF16, // destination buffer
cchUTF16 // size of destination buffer, in WCHAR's
);
ATLASSERT( result != 0 );
if ( result == 0 )
{
AtlThrowLastWin32();
}
// Release internal CString buffer
strUTF16.ReleaseBuffer();
// Return resulting UTF16 string
return strUTF16;
}