1

how to remove xml attribute title using boost's ptree? I had one xml, I tried followed code to remove attribute title and save to new xml but failed(new.xml still had title attribute).

xml:

<?xml version="1.0" encoding="utf-8"?>
<tokens title="issues"></tokens>

the code:

 ptree pt;
 read_xml("C://old.xml", pt);

 pt.erase("tokens.<xmlattr>.title"); //try one
 pt.erase("tokens.<xmlattr>"); //try two

 write_xml("C://new.xml", pt);

is there no any methods for boost ptree to remove attribute?

jiafu
  • 6,338
  • 12
  • 49
  • 73
  • [This](http://coliru.stacked-crooked.com/a/38a39a6d2b68757e) seems to work (I think it's because `erase` can only affect the immediate children of the `ptree`, but I'm not sure). If you tag your question with [tag:boost-propertytree], you'll have a better chance to find an expert on the library. – llonesmiz Feb 01 '14 at 23:14

1 Answers1

2

You can try something like this (with proper error handling):

#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/exceptions.hpp>
#include <sstream>
#include <iostream>

using namespace boost;
using namespace  boost::property_tree;
using namespace std;


int main()
{
    ptree pt;
    {
        std::stringstream strm;
        strm << "<?xml version='1.0' encoding='utf-8'?> <tokens title='issues'></tokens>";
        read_xml(strm, pt);
    }

    pt.find("tokens")->second.erase("<xmlattr>");

    write_xml(cout, pt, xml_writer_make_settings(' ', 2));
}

Output:

$ ./test
<?xml version="1.0" encoding="utf-8"?>
<tokens/>
AlexT
  • 1,413
  • 11
  • 11
  • 1
    Or you can use: pt.get_child("tokens").erase(""); – AlexT Feb 04 '14 at 11:53
  • how to delete one of xmlattrs but not all xmlattrs? 3ks – jiafu Feb 06 '14 at 08:05
  • @jiafu to remove single attribute you can use: `pt.get_child("tokens.").erase("title");` – AlexT Feb 06 '14 at 08:37
  • but,why I can't delete by pt.erase("tokens..title"); – jiafu Feb 06 '14 at 08:47
  • 1
    @jiafu method erase() accepts key_type or iterator as parameter (not path_type). I guess this is because path can be ambiguous (if some of the nodes have the same names) so property_tree interface prevents from unexpected removing of elements. See [basic_tree](http://www.boost.org/doc/libs/1_41_0/doc/html/boost/property_tree/basic_ptree.html) definition. – AlexT Feb 06 '14 at 08:55
  • I had accept your answer and you can improve your answer by our comments.Many thanks to you! – jiafu Feb 06 '14 at 08:59