PugiXML C++获取元素(或标记)的内容

Gre*_*ego 1 c++ xml-parsing pugixml

我正在使用Visual Studio 2010在C++中使用PugiXML来获取元素的内容,但问题是当它看到"<"时它停止获取值,因此它没有获得值,它只是得到内容直到达到"<"字符,即使"<"没有关闭其元素.我希望它到达它的结束标记,即使它忽略标记,但至少只有内部标记内的文本.

如果我获取元素,我也想知道如何获取外部XML

pugi :: xpath_node_set tools = doc.select_nodes("/ mesh/bounds/b"); 我该怎么做才能得到"链接到这里"的全部内容

这个内容与此处给出的内容相同:

#include "pugixml.hpp"

#include <iostream>
#include <conio.h>
#include <stdio.h>

using namespace std;

int main//21
    () {
    string source = "<mesh name='sphere'><bounds><b id='hey'> <a DeriveCaptionFrom='lastparam' name='testx' href='http://www.google.com'>Link Till here<b>it will stop here and ignore the rest</b> text</a></b> 0 1 1</bounds></mesh>";

    int from_string;
    from_string = 1;

    pugi::xml_document doc;
    pugi::xml_parse_result result;
    string filename = "xgconsole.xml";
    result = doc.load_buffer(source.c_str(), source.size());
    /* result = doc.load_file(filename.c_str());
    if(!result){
        cout << "File " << filename.c_str() << " couldn't be found" << endl;
        _getch();
        return 0;
    } */

        pugi::xpath_node_set tools = doc.select_nodes("/mesh/bounds/b/a[@href='http://www.google.com' and @DeriveCaptionFrom='lastparam']");

        for (pugi::xpath_node_set::const_iterator it = tools.begin(); it != tools.end(); ++it) {
            pugi::xpath_node node = *it;
            std::cout << "Attribute Href: " << node.node().attribute("href").value() << endl;
            std::cout << "Value: " << node.node().child_value() << endl;
            std::cout << "Name: " << node.node().name() << endl;

        }

    _getch();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

Attribute Href: http://www.google.com
Value: Link Till here
Name: a
Run Code Online (Sandbox Code Playgroud)

我希望我很清楚,先谢谢你

zeu*_*xcg 6

我的通灵能力告诉我你想知道如何获得节点的所有孩子(也就是内部文本)的连接文本.

最简单的方法是使用XPath:

pugi::xml_node node = doc.child("mesh").child("bounds").child("b");
string text = pugi::xpath_query(".").evaluate_string();
Run Code Online (Sandbox Code Playgroud)

显然你可以编写自己的递归函数来连接子树中的PCDATA/CDATA值; 使用内置的递归遍历工具,例如find_node,也可以使用(使用C++ 11 lambda语法):

string text;
text.find_node([&](pugi::xml_node n) -> bool { if (n.type() == pugi::node_pcdata) result += n.value(); return false; });
Run Code Online (Sandbox Code Playgroud)

现在,如果要获取标记的全部内容(也称为外部xml),可以将节点输出到字符串流,即:

ostringstream oss;
node.print(oss);
string xml = oss.str();
Run Code Online (Sandbox Code Playgroud)

获取内部xml将需要遍历节点的子节点并将其外部xml附加到结果,即

ostringstream oss;
for (pugi::xml_node_iterator it = node.begin(); it != node.end(); ++it)
    it->print(oss);
string xml = oss.str();
Run Code Online (Sandbox Code Playgroud)