Search code examples
c++xmlpugixml

Add xml text structure to xml document


I have a loaded pugi::xml_document with e.g. <node></node> and want to add xml text structure to this pugi xml doc!

example for xml text structure: (stored in std::string)

<cmd name="Test"><tag>some text</tag></cmd>

Final xml doc should look like this:

<node><cmd name="Test"><tag>some text</tag></cmd></node>

What's the best way to do this in pugixml?

Thank you!


Solution

  • Some function to load the doc (<node></node>):

    bool Class::ReadXmlString(std::string xml)
    {
        try
        {               
            pugi::xml_parse_result parseResult = m_xmlDoc->load(xml.c_str());    
            return parseResult;         
        }
        catch(std::exception &exp) 
        {       
            return false; 
        }
    }
    

    function to add e.g.: <cmd name="Test"><tag>some text</tag></cmd>

    bool Class::AddFragment(std::string node, std::string xmlValue)
    {
        try
        {
            //  temporary document to parse the data from a string
            pugi::xml_document doc;
            if (!doc.load_buffer(xmlValue.c_str(), xmlValue.length())) return false;
    
            // select node from class member pugi::xml_document
            pugi::xml_node xmlNode = m_xmlDoc->select_single_node(("//" + node).c_str()).node();
    
            for (pugi::xml_node child = doc.first_child(); child; child = child.next_sibling())
            {
                xmlNode.append_copy(child);
            }
        }
        catch(std::exception &exp)
        {       
            return false;
        }
    }