- // xml_test1.cpp : 定义控制台应用程序的入口点。
- //
- #include "stdafx.h"
- #include <windows.h>
- #include <vector>
- #include <string>
- #include "pugixml.hpp"
- #pragma comment(lib,"pugixmld.lib")
- int _tmain(int argc,_TCHAR* argv[])
- {
- pugi::xml_document doc;
- // 加载xml文件
- pugi::xml_parse_result ret = doc.load_file(_T("test.xml"));
- pugi::xml_node Messages = doc.child("MyApp").child("Messages");
- std::vector<std::pair<std::string,std::string> > vecNode;
- // 读取原有的Welcome 节点和Farewell节点,并保存其值
- for (pugi::xml_node Plugin = Messages.first_child(); Plugin; Plugin = Plugin.next_sibling())
- {
- typedef std::pair<std::string,std::string> string_Pair;
- std::string strNodeName = Plugin.name();
- std::string strValue = Messages.child_value(strNodeName.c_str());
- vecNode.push_back(string_Pair(strNodeName,strValue));
- }
- pugi::xml_node window = doc.child("MyApp").child("Windows");
- for (int i =0;i<vecNode.size();i++)
- {
- // 添加Welcome 节点和Farewell节点
- pugi::xml_node new_node = window.append_child(vecNode[i].first.c_str());
- new_node.append_child(pugi::node_pcdata).set_value(vecNode[i].second.c_str());
- // 添加param 节点
- pugi::xml_node param = window.insert_child_before("param",new_node);
- param.append_attribute("name") = "version";
- param.append_attribute("value") = 1.1;
- param.insert_attribute_after("type",param.attribute("name")) = "float";
- }
- doc.save_file(_T("test.xml"));
- getchar();
- return 0;
- }
xml 文件:
- <?xml version="1.0"?>
- <MyApp>
- <Messages>
- <Welcome>Welcome to MyApp</Welcome>
- <Farewell>Thank you for using MyApp</Farewell>
- </Messages>
- <Windows>
- <Window name="MainFrame" x="5" y="15" w="400" h="250" />
- <param name="version" type="float" value="1.1" />
- <Welcome>Welcome to MyApp</Welcome>
- <param name="version" type="float" value="1.1" />
- <Farewell>Thank you for using MyApp</Farewell>
- </Windows>
- </MyApp>