parse()方法解析xml字符串
std::string strResponce;
strResponce = _T("<commands><command name="ReleaseTemplate" id="123456"><param name="id" value="123456"></param></command><command id="123457"><param name="id" value="123457"></param></command></commands>");
const char *p = strResponce.c_str();
TiXmlDocument* xmlDocument = new TiXmlDocument();
xmlDocument->Parse(p, 0, TIXML_DEFAULT_ENCODING);
xmlDocument->SaveFile(_T("d:\myfile.xml"));
大致要做的内容是这样,我发送一http请求,得到一个xml格式字符串
<?xml version="1.0" encoding="UTF-8" ?>
<result>
<error>
23
</error>
<prepayValidTime></prepayValidTime>
<cardMegNum></cardMegNum>
<prepay>0</prepay>
<merPoint>0</merPoint>
<customerName></customerName>
<recordCount>
</recordCount>
<reverseRecordCount>
</reverseRecordCount>
<totalAmount>
</totalAmount>
<amount>
</amount>
</result>
//tinyxml
try
{
const char *szFile = "test.xml"; //通过文件解析XML
TiXmlDocument *spXmlDoc = new TiXmlDocument(szFile);
bool bLoad = spXmlDoc->LoadFile();
if (!bLoad)
{
return false;
}
/*
const char *strQryResult = ""; //通过字符串解析XML。strQryResult 为返回XML字符串
TiXmlDocument *spXmlDoc = new TiXmlDocument();
spXmlDoc->Parse(strQryResult);
*/
TiXmlNode* pNode = NULL;
TiXmlElement *spElement = NULL;
const char * szXmlVaule = NULL;
pNode = spXmlDoc->FirstChild("result")->FirstChildElement("error");
if (NULL == pNode)
return 0;
spElement = pNode->ToElement();
szXmlVaule = spElement->GetText();
spElement = pNode->NextSibling("prepayValidTime")->ToElement();
szXmlVaule = spElement->GetText();
spElement = pNode->NextSibling("cardMegNum")->ToElement();
szXmlVaule = spElement->GetText();
spElement = pNode->NextSibling("prepay")->ToElement();
szXmlVaule = spElement->GetText();
// ....
spElement = pNode->NextSibling("amount")->ToElement();
szXmlVaule = spElement->GetText();
if(szXmlVaule) //判断取得的值是否为空
cout << szXmlVaule << endl;
}
catch(...)
{
// ....
}
/////////////////////////////////////////////////////
TinyXml提供了多种方法,可以从不同角度,多方面地去解析XML