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

PugiXML C++ getting content of an element (or a tag)

本文关键字:C++ 获取 元素 PugiXML      更新时间:2023-10-16

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

我还想知道如何获得外部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;
}

这是输出:

Attribute Href: http://www.google.com
Value: Link Till here
Name: a

我希望我足够清楚,提前感谢

我的灵力告诉我,你想知道如何获得节点所有子节点的连接文本(也称为内部文本)。

最简单的方法是使用XPath:

pugi::xml_node node = doc.child("mesh").child("bounds").child("b");
string text = pugi::xpath_query(".").evaluate_string();

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

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

现在,如果您想获得标签的全部内容(也称为外部xml),您可以输出一个节点到字符串流,即:

ostringstream oss;
node.print(oss);
string xml = oss.str();

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

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

这就是XML的工作原理。您不能将<>嵌入您的价值观中。转义它们(例如,使用&lt;&gt;等HTML实体)或定义CDATA部分。

我在解析包含所有元素和子节点的子树的问题上遇到了很多困难——最简单的方法几乎就是这里显示的:

你应该使用这个代码:

ostringstream oss;
oNode.print(oss, "", format_raw);
sResponse = oss.str();

如果需要,请在每个函数之前使用pugi::,而不是oNode。