要解析的xml数据如下:
string strXml = " \ <?xml version="1.0" ?> \ <object> \ <string name = "id">145678249</string> \ <object name="attrs"> \ <string name="account">zhou</string> \ <array name="to">xia</array> \ <string name="subject">test</string> \ <string name="content">gan</string> \ </object> \ </object> ";对于这种内存中的xml字符串,可以用TiXmlDocument类的Parse()接口来直接解析,如下:
TiXmlDocument *pXml = new TiXmlDocument(); pXml->Parse( strXml.c_str() );调用Parse()后,xml字符串就被解析成xml文档树,可以直接调用tinyxml的相关接口来进行操作了。比较完整的代码如下:
const char *GetXmlValue(TiXmlHandle *pXmlHandle,char *ElementName,char *ElementAttrName,char *ElementAttrValue) { TiXmlElement *pObjElement = pXmlHandle->FirstChild("object").FirstChild("object").ToElement(); TiXmlElement *pElement = NULL; std::string strAttrValue; for( pElement = pObjElement->FirstChildElement(ElementName); pElement; pElement = pElement->NextSiblingElement(ElementName) ) { //获取当前元素的属性值 strAttrValue = pElement->Attribute(ElementAttrName); if(strAttrValue == ElementAttrValue) { //获取当前元素的文本内容 return pElement->GetText(); } } return NULL; } int main() { TiXmlDocument *pXml = new TiXmlDocument(); pXml->Parse( strXml.c_str() ); //用TiXmlHandle类来访问Xml文档树(针对xml字符串) TiXmlHandle xmlHandle(pXml); //strUser == "zhou" string strUser = GetXmlValue(&xmlHandle,"string","name","account"); //strTo == "xia" string strTo = GetXmlValue(&xmlHandle,"to"); //strSub == "test" string strSub = GetXmlValue(&xmlHandle,"subject"); //strCon == "gan" string strCon = GetXmlValue(&xmlHandle,"content"); delete pXml; }原文链接:/xml/297381.html