[杂项]pugi::xml获取xml中的注释节点
前言
想到学习xml时的一句话,xml中注释也会被算作一个节点。那么我们就可以通过 pugixml 把注释节点获取出来,
<?xml version="1.0"?>
<mesh name="mesh_root"><!--这是一个注释节点-->some text<![CDATA[someothertext]]>some more text<node attr1="value1" attr2="value2" /><node attr1="value3" attr2="value4" /><node attr1="value2"><innernode /></node>
</mesh>
代码
pugi::xml_document doc;pugi::xml_parse_result result = doc.load_file("D:/pugixml-1.14/docs/samples/tree.xml");if(result){pugi::xml_node rootNode = doc.document_element();const char* commont = rootNode.first_child().value();qDebug() << "commont : " << commont;}
输出结果
commont : some text
并不是我们想要的结果
思路打开
我们直接去pugixml官网 quickstart。直接在页面上搜索 commont
看着代码确实看不出来东西,继续思路打开,找到源文件
modify_base.cpp
#include "pugixml.hpp"#include <string.h>
#include <iostream>int main()
{pugi::xml_document doc;if (!doc.load_string("<node id='123'>text</node><!-- comment -->", pugi::parse_default | pugi::parse_comments)) return -1;// tag::node[]pugi::xml_node node = doc.child("node");// change node namestd::cout << node.set_name("notnode");std::cout << ", new node name: " << node.name() << std::endl;// change comment textstd::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 commentstd::cout << node.set_value("1") << ", " << doc.last_child().set_name("2") << std::endl;// end::node[]// tag::attr[]pugi::xml_attribute attr = node.attribute("id");// change attribute name/valuestd::cout << attr.set_name("key") << ", " << attr.set_value("345");std::cout << ", new attribute: " << attr.name() << "=" << attr.value() << std::endl;// we can use numbers or booleansattr.set_value(1.234);std::cout << "new attribute value: " << attr.value() << std::endl;// we can also use assignment operators for more concise codeattr = true;std::cout << "final attribute value: " << attr.value() << std::endl;// end::attr[]
}// vim:et
if (!doc.load_string("<node id='123'>text</node><!-- comment -->", pugi::parse_default | pugi::parse_comments)) return -1;
ok问题直接解决,原来是在加载xml时要配置对应的选项。很多时候遇到问题,不要觉得就没有办法,一定要把思路打开,说不定问题很简单。