2012-03-21 20 views
1

C++でVisual Studio 2010を使用して要素の内容を取得するPugiXMLを使用していますが、要素の内容を取得するためにPugiXMLが停止することがあります"<"は値を取得しないので、 "<"が要素を閉じていなくても "<"文字に達するまでコンテンツを取得します。タグを無視しても終了タグに到達するまで取得したいが、内側のタグの中のテキストは少なくとも、それを取得したい。要素(またはタグ)の内容を取得するPugiXML C++

そして私はまた、私は要素にフェッチ場合例えば外部XMLを取得する方法を知っていただきたいと思い

プーギー:: 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の仕組みです。 <または>をあなたの値に埋め込むことはできません。それらをエスケープするか(&lt;&gt;などのHTMLエンティティを使用)、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のラムダ構文を使用して)うまくいく:

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 ::を使用します。

関連する問題