pugixml读写 遍历节点方法

// test.cpp : Defines the entry point for the console application.

//test.xml
/*

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book name="0">
<title lang="eng">Harry Potter</title>
<price>29.99</price>
<test1>test_1</test1>
<test2>test_2</test2>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>

*/
#include "stdafx.h"
#include <iostream>
#include "pugixml.hpp"


int _tmain(int argc, _TCHAR* argv[])
{
	pugi::xml_document doc;
	if (!doc.load_file("test.xml")) return -1;

	pugi::xpath_node_set tools = doc.select_nodes("/bookstore/book[@name='0']"); //筛选出所有 name=0的book节点

	std::cout <<tools.size()<< "  Tools:\n";

	
	//book 项
	for (pugi::xpath_node_set::const_iterator it = tools.begin(); it != tools.end(); ++it)
	{
		pugi::xml_node nodeTmp = it->node();
		//book 节点名和值
		std::cout<< nodeTmp.name()<<" -- "<<nodeTmp.text().as_string()<<std::endl;

		//book节点属性
		for (pugi::xml_attribute attr = nodeTmp.first_attribute(); attr; attr = attr.next_attribute())  
		{  
			std::cout << " " << attr.name() << "=" << attr.value() <<"\n";  
		}
		
		//book 子节点集合
		pugi::xml_object_range<pugi::xml_node_iterator> child = nodeTmp.children();

		// book/title  book/price  ....等子节点 
	    pugi::xml_node_iterator iterchild = child.begin();
		for (iterchild; iterchild != child.end(); iterchild++)
		{
			
			std::cout<< iterchild->name()<<" -- "<<iterchild->text().as_string()<<std::endl;
		}
		
	}

	return 0;
}

//输出结果
1  Tools:
book --
name=0
title -- Harry Potter
price -- 29.99
test1 -- test_1
test2 -- test_2
请按任意键继续. . .

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值