tinyXml直接解析XML字符串

时间:2024-01-20 08:41:09

一直都用tinyxml直接LoadFile来解析XML,发现原来也可以直接解析XML字符串。

XML文件:

 <?xml version=\"1.0\" encoding=\"utf-8\"?>
<person>
<name>Alan</name>
<age>26</age>
<height>165</height>
<weight>65</weight>
<introduction>C senior engineer</introduction>
</person>

解析代码:

 #include <stdio.h>
#include "tinyxml.h" int tinyxmlTest(void); int main(int argc, char* argv[])
{
tinyxmlTest();
return ;
} int tinyxmlTest(void)
{
#if (1)
char* xmlStr = "\
<person>\
<name>Alan</name>\
<age></age>\
<height></height>\
<weight></weight>\
<introduction>C senior engineer</introduction>\
</person>"; TiXmlDocument* myDocument = new TiXmlDocument();
myDocument->Parse(xmlStr); #else
TiXmlDocument* myDocument = new TiXmlDocument();
myDocument->LoadFile("person.xml");
#endif
//.....person.....
TiXmlElement* rootElement = myDocument->RootElement();
if (rootElement == NULL || strcmp(rootElement->Value(), "person"))
return ;
printf("%s:\t%s\n", rootElement->Value(), rootElement->GetText()); //.....name.....
TiXmlElement* element = rootElement->FirstChildElement();
if (element == NULL || strcmp(element->Value(), "name"))
return ;
printf("%s:\t%s\n", element->Value(), element->GetText()); //.....age.....
element = element->NextSiblingElement();
if (element == NULL || strcmp(element->Value(), "age"))
return ;
printf("%s:\t%s\n", element->Value(), element->GetText()); //.....height.....
element = element->NextSiblingElement();
if (element == NULL || strcmp(element->Value(), "height"))
return ;
printf("%s:\t%s\n", element->Value(), element->GetText()); //.....weight.....
element = element->NextSiblingElement();
if (element == NULL || strcmp(element->Value(), "weight"))
return ;
printf("%s:\t%s\n", element->Value(), element->GetText()); //.....introduction.....
element = element->NextSiblingElement();
if (element == NULL || strcmp(element->Value(), "introduction"))
return ;
printf("%s:\t%s\n\n", element->Value(), element->GetText()); return ;
}

顺便推荐其他博友对tinyxml使用介绍

http://qaohao.iteye.com/blog/496237