2012-03-21 155 views
1

嗯,我使用C中PugiXML ++使用Visual Studio 2010来获得元素的含量,但事情是,它停下来所获得的价值是看到了当“<”,所以它没有得到的价值,它只是直到它到达即使“<”不打烊其元素的“<”角色获得的内容。我希望它得到它,直到它达到它的结束标记,即使它忽略了标记,但只有内部标记内部的文本,至少。PugiXML C++元素(或标签)的获取内容

而且我也想知道如何获得例如外XML,如果我取元素

pugi :: xpath_node_set工具= doc.select_nodes(“/网/边界/ 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 

我希望我是再清楚不过, 在此先感谢

回答

2

这就是如何将XML的作品。你不能在你的价值观嵌入<>权利。转义(例如,使用HTML实体像&lt;&gt;)或定义CDATA section

4

我的精神力量告诉我你想知道如何获得节点(又名内部文本)的所有儿童的级联文本。

做到这一点的最简单方法是使用XPath这样的:

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

很明显,你可以写一个串接从树的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; }); 

现在,如果你想获得该标签的所有内容(又名外部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(); 
1

我挣扎很多 在解析树在内的所有元素和子节点的问题 - 最简单的方法在这里几乎出了什么:

您应使用此代码:

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

而是oNode的使用所需的节点,如果需要,在每个功能之前使用pugi ::。