接着上一篇,我们来读取这样一共xml文件:
<?xml version="1.0" encoding="GBK" ?>
<root>
<host checked="true" station="1001">www.baidu.com</host>
<client>
<name>余生皆假期</name>
<id>10000</id>
</client>
</root>
直接使用这两个函数读取到文件和root指针,值得注意的是,我们必须每一步都判断指针是否可用,如果把空指针运用到下列操作会造成很严重的错误。
TiXmlDocument xml_doc;
if (!xml_doc.LoadFile("xml_doc.xml")) //使用LoadFile获得文件
{
return -1;
}
TiXmlElement* xml_root = xml_doc.RootElement(); //或者root指针
if (NULL == xml_root)
{
return -1;
}
首先获得“host”属性的指针,然后获得数据和属性的值
TiXmlElement* xml_host = xml_root->FirstChildElement("host"); //使用这个函数得到root下下的“host”元素的指针
if(xml_host == null)
{
return -1;
}
const char* text = xml_host->GetText(); //得到host的数据
const char* aChecked = xml_host->Attribute("checked"); //得到“host”名为“checked”属性的值
const char* astation = xml_host->Attribute("station");//也是得到属性,同上
printf("text = %s, ch = %s, as = %s\n", text, aChecked, astation);//打印即可
对于兄弟元素,比如:
<?xml version="1.0" encoding="GBK" ?>
<root>
<phone>12111</phone>
<phone>34111</phone>
<phone>56111</phone>
<phone>78111</phone>
</root>
我们使用while循环依次读取
TiXmlElement* xml_phone = xml_root->FirstChildElement("phone");
while (xml_phone) //直到没有下一个,xml_phone为null为止
{
const char* name = xml_phone->GetText();
xml_phone = xml_phone->NextSiblingElement("phone"); //使得xml_phone指向下一个兄弟元素
printf("name = %s\n", name);
}