一直都用tinyxml直接LoadFile來解析XML,發現原來也可以直接解析XML字符串。
XML文件:
1 <?xml version=\"1.0\" encoding=\"utf-8\"?> 2 <person> 3 <name>Alan</name> 4 <age>26</age> 5 <height>165</height> 6 <weight>65</weight> 7 <introduction>C senior engineer</introduction> 8 </person>
解析代碼:
1 #include <stdio.h> 2 #include "tinyxml.h" 3 4 int tinyxmlTest(void); 5 6 int main(int argc, char* argv[]) 7 { 8 tinyxmlTest(); 9 return 1; 10 } 11 12 int tinyxmlTest(void) 13 { 14 #if (1) 15 char* xmlStr = "\ 16 <person>\ 17 <name>Alan</name>\ 18 <age>26</age>\ 19 <height>165</height>\ 20 <weight>65</weight>\ 21 <introduction>C senior engineer</introduction>\ 22 </person>"; 23 24 TiXmlDocument* myDocument = new TiXmlDocument(); 25 myDocument->Parse(xmlStr); 26 27 #else 28 TiXmlDocument* myDocument = new TiXmlDocument(); 29 myDocument->LoadFile("person.xml"); 30 #endif 31 //.....person..... 32 TiXmlElement* rootElement = myDocument->RootElement(); 33 if (rootElement == NULL || strcmp(rootElement->Value(), "person")) 34 return 0; 35 printf("%s:\t%s\n", rootElement->Value(), rootElement->GetText()); 36 37 //.....name..... 38 TiXmlElement* element = rootElement->FirstChildElement(); 39 if (element == NULL || strcmp(element->Value(), "name")) 40 return 0; 41 printf("%s:\t%s\n", element->Value(), element->GetText()); 42 43 //.....age..... 44 element = element->NextSiblingElement(); 45 if (element == NULL || strcmp(element->Value(), "age")) 46 return 0; 47 printf("%s:\t%s\n", element->Value(), element->GetText()); 48 49 //.....height..... 50 element = element->NextSiblingElement(); 51 if (element == NULL || strcmp(element->Value(), "height")) 52 return 0; 53 printf("%s:\t%s\n", element->Value(), element->GetText()); 54 55 //.....weight..... 56 element = element->NextSiblingElement(); 57 if (element == NULL || strcmp(element->Value(), "weight")) 58 return 0; 59 printf("%s:\t%s\n", element->Value(), element->GetText()); 60 61 //.....introduction..... 62 element = element->NextSiblingElement(); 63 if (element == NULL || strcmp(element->Value(), "introduction")) 64 return 0; 65 printf("%s:\t%s\n\n", element->Value(), element->GetText()); 66 67 return 1; 68 }
順便推薦其他博友對tinyxml使用介紹
http://qaohao.iteye.com/blog/496237