Domanda

I'm using RapidXML to parse XML files and read nodes content but I don't want to read values inside a node, I need to read the content of specific XML nodes "as XML" not as parsed values.

Example :

<node1>
    <a_lot_of_xml>
      < .... >
    </a_lot_of_xml>
</node1>

I need to get the content of node1 as :

<a_lot_of_xml>
    < .... >
</a_lot_of_xml>

What I tired :

I tried something but its not really good in my opinion, its about to put in node1, the path of an other xml file to read, I did like this :

<file1ToRead>MyFile.xml</file1ToRead>

And then my c++ code is the following :

ifstream file(FileToRead);

stringstream buffer; buffer << file.rdbuf();

But the problem is users will have a lot of XML files to maintain and I just want to use one xml file.

È stato utile?

Soluzione

I think "a lot of XML files" is a better way, so you have a directory of all xml files, you can read the xml file when you need it, good for performance. Back to the problem, can use the rapidxml::print function to get the xml format.

bool test_analyze_xml(const std::string& xml_path)
{
    try
    {
        rapidxml::file<> f_doc(xml_path.c_str());  
        rapidxml::xml_document<> xml_doc;
        xml_doc.parse<0>(const_cast<char*>(f_doc.data()));
        rapidxml::xml_node<>* node_1 = xml_doc.first_node("node1"); 
        if(node_1 == NULL)
        {
            return false;
        }
        rapidxml::xml_node<>* plain_txt = node_1->first_node("a_lot_of_xml"); 
        if (plain_txt == NULL)
        {
            return false;
        }
        std::string xml_data;
        rapidxml::print(std::back_inserter(xml_data), *plain_txt, rapidxml::print_no_indenting);  //the xml_data is XML format.
    }
    catch (...)
    {
        return false;
    }
    return true;
}

Altri suggerimenti

I'm unfamiliar with rapidxml, but I have done this with tinyxml2. The trick is to read out node1 and then create a new XMLDoc (using tinyxml2 terms here) that contains everything inside of node1. From there, you can use their XMLPrinter class to convert your new XMLDoc (containing everything in node1) to a string.

tinyxml2 is a free download.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top