1.8 Acknowledgements(致谢)
I would like to thank Arseny Kapoulkine for his work on pugixml, which was an inspiration for this project. Additional thanks go to Kristen Wegner for creating pugxml, from which pugixml was derived. Janusz Wohlfeil kindly ran RapidXml speed tests on hardware that I did not have access to, allowing me to expand performance comparison table.
2. Two Minute Tutorial(两分钟教程)
2.1 Parsing(分析)
下面的代码示范了RapidXml分析一个以0结尾的字符串text:
using namespace rapidxml;
xml_document<> doc; // 字符类型默认为char
doc.parse<0>(text); // 0表示默认分析标记
doc对象现在是一个DOM树,代表已分析的XML。因为所有的RadpidXml接口都包含在命名空间 rapidxml中,用户要么加入此命令空间,要么使用完整的命名(译注:即要使用doc必须使用 rapidxml::xml_docment<> doc),类xml_document代表一个DOM层次的根节点。除了是公共的继承点,它还是一个xml_node 和memory_pool。xml_document::parse()函数的模板参数是用来指定分析标记的,它可以用来对分析器进行微调。但要注意,标记必须是一个编译器的常数。
2.2 Accessing The DOM Tree(访问DOM树)
要访问DOM树,使用xml_node和xml_attribute类中的方法即可:
cout << "Name of my first node is: " << doc.first_node()->name() << "\n";
xml_node<> *node = doc.first_node("foobar");
cout << "Node foobar has value " << node->value() << "\n";
for (xml_attribute<> *attr = node->first_attribute();
attr; attr = attr->next_attribute())
{
cout << "Node foobar has attribute " << attr->name() << " ";
cout << "with value " << attr->value() << "\n";
}
2.3 Modifying The DOM Tree(修改DOM树)
分析器生成的DOM树完全可以修改。可以增加和删除节点和属性,还有他们的内容。下面的例子创建了一个HTML文档,并有个单独的链接到google.com网站:
xml_document<> doc;
xml_node<> *node = doc.allocate_node(node_element, "a", "Google");
doc.append_node(node);
xml_attribute<> *attr = doc.allocate_attribute("href", "google.com");
node->append_attribute(attr);