1

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?

sehe
  • 374,641
  • 47
  • 450
  • 633

1 Answers1

1

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>
sehe
  • 374,641
  • 47
  • 450
  • 633
  • thank you very much. But I have a small question. If the `` is a random name, How can I get the father node of `` node? – Thế Hải Nguyễn Jun 14 '17 at 10:21
  • @ThếHảiNguyễn Huh. You just write the code to do it. Or, you could use an XML library, instead of a PropertyTree library. – sehe Jun 14 '17 at 12:36