Search code examples
xmlboostboost-propertytree

How to delete the last xml node and its child with boost lib?


I want to remove a node from an XML file.

XML string looks like:

<BookData>
   <Book><Author>A1<Author><Name>B1</Name><Price>C1</Price></Book>
   <Book><Author>A2<Author><Name>B2</Name><Price>C2</Price></Book>
     ...
   <Book><Author>A(n-1)<Author><Name>B(n-1)</Name><Price>C(n-1)</Price></Book>
   <Book><Author>A(n)<Author><Name>B(n)</Name><Price>C(n)</Price></Book> 
</BookData>

I want it to end up like this.

 <BookData>
       <Book><Author>A1<Author><Name>B1</Name><Price>C1</Price></Book>
       <Book><Author>A2<Author><Name>B2</Name><Price>C2</Price></Book>
         ...
       <Book><Author>A(n-1)<Author><Name>B(n-1)</Name><Price>C(n-1)</Price></Book> 
    </BookData>

How can I do that with boost lib?


Solution

  • You can use the reverse-iterator rbegin(), but the conversion to its base iterator is always a bit tricky:

        auto& root = pt.get_child("BookData");
        root.erase(std::next(root.rbegin()).base());
    

    cppreference has a neat illustration: enter image description here

    See Live On Coliru

    #include <iostream>
    #include <boost/property_tree/xml_parser.hpp>
    
    int main() {
        std::istringstream iss(R"(
    <BookData>
       <Book><Author>A1</Author><Name>B1</Name><Price>C1</Price></Book>
       <Book><Author>A2</Author><Name>B2</Name><Price>C2</Price></Book>
       <Book><Author>A(n-1)</Author><Name>B(n-1)</Name><Price>C(n-1)</Price></Book>
       <Book><Author>A(n)</Author><Name>B(n)</Name><Price>C(n)</Price></Book> 
    </BookData>
    )");
    
        boost::property_tree::ptree pt;
        read_xml(iss, pt);
    
        auto& root = pt.get_child("BookData");
        root.erase(std::next(root.rbegin()).base());
    
        write_xml(std::cout, pt, boost::property_tree::xml_writer_make_settings<std::string>(' ', 4));
    }
    

    Prints

    <?xml version="1.0" encoding="utf-8"?>
    <BookData>
    
        <Book>
            <Author>A1</Author>
            <Name>B1</Name>
            <Price>C1</Price>
        </Book>
        <Book>
            <Author>A2</Author>
            <Name>B2</Name>
            <Price>C2</Price>
        </Book>
        <Book>
            <Author>A(n-1)</Author>
            <Name>B(n-1)</Name>
            <Price>C(n-1)</Price>
        </Book>
    </BookData>