// You can use load_buffer_inplace to load document from mutable memory block; the block's lifetime must exceed that of document char* buffer = newchar[size]; memcpy(buffer, source, size);
// The block can be allocated by any method; the block is modified during parsing pugi::xml_parse_result result = doc.load_buffer_inplace(buffer, size);
// You have to destroy the block yourself after the document is no longer used delete[] buffer;
从 stream 中加载
1 2
std::ifstream stream("weekly-utf-8.xml"); pugi::xml_parse_result result = doc.load(stream);
// change node name std::cout << node.set_name("notnode"); std::cout << ", new node name: " << node.name() << std::endl;
// change comment text std::cout << doc.last_child().set_value("useless comment"); std::cout << ", new comment text: " << doc.last_child().value() << std::endl;
// we can't change value of the element or name of the comment std::cout << node.set_value("1") << ", " << doc.last_child().set_name("2") << std::endl; pugi::xml_attribute attr = node.attribute("id");
// we can use numbers or booleans attr.set_value(1.234); std::cout << "new attribute value: " << attr.value() << std::endl;
// we can also use assignment operators for more concise code attr = true; std::cout << "final attribute value: " << attr.value() << std::endl;
// CAUTION // attribute() and child() functions do not add attributes or nodes // to the tree, so code like node.attribute("id") = 123; will not do // anything if node does not have an attribute with name "id". // Make sure you’re operating with existing attributes/nodes by // adding them if necessary.
添加新属性或节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// add node with some name pugi::xml_node node = doc.append_child("node");
// add description node with text child pugi::xml_node descr = node.append_child("description"); descr.append_child(pugi::node_pcdata).set_value("Simple node");
// add param node before the description pugi::xml_node param = node.insert_child_before("param", descr);