【问题标题】:Poco XML - Get node inner XMLPoco XML - 获取节点内部 XML
【发布时间】:2017-02-19 04:36:14
【问题描述】:

我有以下示例 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>

【问题讨论】:

    标签: c++ xml poco-libraries


    【解决方案1】:

    Poco 中不存在这样的功能,但您可以用最少的代码行数创建自己的功能。 您可以在documentation 中获取有关 Node 方法的信息。

    您需要将节点的名称与子节点的名称和值的属性连接起来。 获取属性使用方法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);
        }
    

    【讨论】:

    • 谢谢,它有效。我不敢相信现在还没有这样的方法——它是如此有用。
    猜你喜欢
    • 2020-06-22
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多