2017-02-19 10 views
1

内側のXMLノードなさい:ポコのXML - 私は、次の例のXMLを持って

<root> 
    <node id="1"> 
     <value>test</value> 
     <value2>test2</value2> 
    </node> 
    <node id="2"> 
     <value>test</value> 
    </node> 
</root> 
私がのstd ::文字列内のノード全体1 XMLコンテンツを取得できますか

私は次のことを試してみた:

Poco:XML:Node *node = xmlDocument->getNodeByPath("/root/node[1]"); 
Poco::XML::XMLString xstr = node->getPocoElement()->innerText; 
string str = Poco::XML::fromXMLString(node->getPocoElement()->innerText); 

そして、それだろう戻って、この:ポコでは、このような機能が存在していません

<node id="1"> 
     <value>test</value> 
     <value2>test2</value2> 
    </node> 

答えて

2

test \n test2 

私はこれを必要とします最小限のコード行で独自のものを作成することができます。 ノードのメソッドについての情報はdocumentationにあります。

サブノードによって名前と値の属性を持つノードの連結名が必要です。 get属性の場合、メソッドattributesを使用します。

getサブノードの場合、方法childNodesを使用します。

コンプリート例:

#include "Poco/DOM/DOMParser.h" 
#include "Poco/DOM/Document.h" 
#include "Poco/DOM/NodeList.h" 
#include "Poco/DOM/NamedNodeMap.h" 
#include "Poco/SAX/InputSource.h" 
#include <iostream> 
#include <fstream> 
#include <string> 

std::string node_to_string(Poco::XML::Node* &pNode,const std::string &tab); 

int main() 
{ 
std::ifstream in("E://test.xml"); 
Poco::XML::InputSource src(in); 
Poco::XML::DOMParser parser; 
auto xmlDocument = parser.parse(&src); 
auto pNode = xmlDocument->getNodeByPath("/root/node[0]"); 

std::cout<<node_to_string(pNode,std::string(4,' '))<<std::endl; 

return 0; 
} 

std::string node_to_string(Poco::XML::Node* &pNode,const std::string &tab) 
    { 
    auto nodeName = pNode->nodeName(); 

    Poco::XML::XMLString result = "<" + nodeName ; 

    auto attributes = pNode->attributes(); 
    for(auto i = 0; i<attributes->length();i++) 
    { 
    auto item = attributes->item(i); 
    auto name = item->nodeName(); 
    auto text = item->innerText(); 
    result += (" " + name + "=\"" + text + "\""); 
    } 

    result += ">\n"; 
    attributes->release(); 

    auto List = pNode->childNodes(); 
    for(auto i = 0; i<List->length();i++) 
    { 
    auto item = List->item(i); 
    auto type = item->nodeType(); 
    if(type == Poco::XML::Node::ELEMENT_NODE) 
    { 
     auto name = item->nodeName(); 
     auto text = item->innerText(); 
     result += (tab + "<" + name + ">" + text + "</"+ name + ">\n"); 
    } 

    } 
    List->release(); 
    result += ("</"+ nodeName + ">"); 
    return Poco::XML::fromXMLString(result); 
    } 
+0

おかげで、それが動作します。私はそのようなメソッドが既に存在しないと信じることはできません。とても有用です。 – Machinegon

関連する問題