2017-02-19 82 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 :: string整個內部節點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); 

,它會返回此:

test \n test2 

我需要這樣的:

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

回答

2

沒有在波索存在這樣的功能,但您可以使用最少的代碼行創建自己的代碼。 關於您可以在documentation中獲得的節點方法的信息。

您需要通過子節點將具有名稱和值的屬性連接起來。 獲取屬性使用方法attributes

獲取子節點使用方法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