2017-06-12 97 views
1

我想從XML文件中刪除節點。如何使用boost lib刪除最後一個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

可以使用反向迭代器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> 
+0

非常感謝。但我有一個小問題。如果''是一個隨機名,我怎樣才能得到''節點的父節點? –

+0

@ThếHảiNguyễnHuh。你只需編寫代碼來完成它。或者,您可以使用XML庫,而不是PropertyTree庫。 – sehe