如何使用boost lib删除最后一个xml节点及其子节点?

时间:2017-06-12 07:25:30

标签: xml boost boost-propertytree

我想从XML文件中删除一个节点。

XML字符串如下所示:

<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>

我希望它最终会像这样。

 <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>

我怎样才能使用boost lib?

1 个答案:

答案 0 :(得分:1)

你可以使用反向迭代器rbegin(),但转换到它的基础迭代器总是有点棘手:

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

cppreference有一个简洁的插图:enter image description here

参见 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));
}

打印

<?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>