码迷,mamicode.com
首页 > 其他好文 > 详细

tinyXml直接解析XML字符串

时间:2015-04-08 14:29:40      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

一直都用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

tinyXml直接解析XML字符串

标签:

原文地址:http://www.cnblogs.com/1024Planet/p/4401929.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!