VC++ XML读写随笔【三】tinyxml读取xml文件教程

本文介绍了一种使用TiXml库解析XML文件的方法,包括如何获取根元素、子元素及其属性值,并通过实例展示了如何遍历兄弟元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

接着上一篇,我们来读取这样一共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);
	}
	

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值