快捷搜索: 王者荣耀 脱发

将XML node转为字符串(C++)

想得到这么一个字符串:

<vtml_phoneme alphabet="x-ntsampa" lang="GER" ph="?al|t@ pOst|Stra:|s@">Alte PoststraÃe</vtml_phoneme>

看到项目用的XML库是TinyXML,我想先生成Node再转为字符串这个方法来的比较直接,于是翻阅网络发现是可以办到的:

TiXmlElement Ele("vtml_phoneme");
TiXmlPrinter printer;
JString strApos(_T("&apos;"));
JString strRes;
Ele.SetAttribute("alphabet", "x-ntsampa");

if (NULL != pNameInfo->m_strPhonemeTag.GetNativeString() && TnAudioConfig::GetInstance().IsUsePhoneme())
{
	std::string strPhonemeTag;
	TnCodeConvertor::WCharToChar(pNameInfo->m_strPhonemeTag.GetNativeString(), strPhonemeTag);
	Ele.SetAttribute("lang", strPhonemeTag.c_str());
}

if (NULL != vSplitPhoneme[0].GetNativeString())
{
	//convert double-quot to single-quot in string
	std::string strSplitPhoneme;
	vSplitPhoneme[0].ReplaceAll(strDoubleQuote, strSingleQuote);
	TnCodeConvertor::WCharToChar(vSplitPhoneme[0].GetNativeString(), strSplitPhoneme);
	Ele.SetAttribute("ph", strSplitPhoneme.c_str());
}

if (NULL != pNameInfo->m_strName.GetNativeString())
{
	std::string strStreetName;
	TnCodeConvertor::WCharToChar(pNameInfo->m_strName.GetNativeString(), strStreetName);
	TiXmlText* pEleText = new TiXmlText(strStreetName.c_str());
	Ele.LinkEndChild(pEleText);
}

Ele.Accept(&printer);
strRes.AppendEx(printer.CStr());

代码中,没有用到xml file生成的方法,直接用TiXmlElement 和TiXmlPrinter 就解决了问题。首先设定其attribute,然后创建了个TiXmlText,作为node中的text并以LinkEndChild将其链接起来。TiXmlElement使用Accept方法接收TiXmlPrinter参数,接着用TiXmlPrinter.CStr()就可以输出字符串了。

不过TinyXML的API及内部处理只支持多字节,不能直接处理宽字符,需要进行转换。 另外,new出来的XML元素并不需要delete,因为一旦挂在再XML树中,会随着根node的析构而删除所有子元素。

经验分享 程序员 微信小程序 职场和发展