// 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
请按任意键继续. . .