被解析的文件为test.xml,文件内容如下:
<?xml version="1.0" encoding="GBK" ?>
<root>
<host checked="true" station="1001">AAA</host>
<client>
<name>xiaoming</name>
<id>200801</id>
</client>
</root>
解析该文件的C++程序如下:
#include <stdio.h>
#include "../tinyxml/tinyxml.h"
int main()
{
// 解析xml
TiXmlDocument xml_doc;
if(!xml_doc.LoadFile("test.xml"))
{
return -1;
}
// 根节点
TiXmlElement* xml_root = xml_doc.RootElement();
if (NULL == xml_root)
{
return -1;
}
// 获取元素的文本与属性
if(0)
{
TiXmlElement* xml_host = xml_root->FirstChildElement("host");
const char* text = xml_host->GetText();
const char* aChecked = xml_host->Attribute("checked");
const char* aStation = xml_host->Attribute("station");
printf("text:%s, check:%s, station:%s\n", text, aChecked, aStation);
}
//
if(1)
{
TiXmlElement* xml_client = xml_root->FirstChildElement("client");
TiXmlElement* xml_clientId = xml_client->FirstChildElement("id");
TiXmlElement* xml_clientName = xml_client->FirstChildElement("name");
const char* text_name = xml_clientName->GetText();
printf("name = %s\n", text_name);
// ...取得id和name的文本 ...
}
return 0;
}