2015-02-06 4 views
1

У меня есть фрагмент кода, который выполняет итерацию над деревом свойств boost (XML).
Мне нужен ptree текущего узла, а не дочерние узлы узла.Получение ptree из boost :: property_tree :: ptree :: iterator

ОБНОВЛЕНИЕ

XML-дерево

<node id="A.html"> 
    <subnode> child A1 </subnode> 
    <subnode> child A2 </subnode> 
</node> 

<node id="B.html"> 
    <subnode> child B1 </subnode> 
    <subnode> child B2 </subnode> 
</node> 

itteration код

void parse_tree(ptree& pt, std::string key) 
{ 
    string nkey; 
    if (!key.empty()) 
    nkey = key + "."; 

    ptree::const_iterator end = pt.end(); 
    for(ptree::iterator it = pt.begin(); it != end; ++it){ 

     //if the node's id is a .html filname, save the node to file 
     string id = it->second.get("<xmlattr>.id",""); 

     if(id.find("B.html") != std::string::npos){ //Let's just test for "B.html" 
      write_xml("test.html", pt);   //saves entire tree 
      write_xml("test.html", it->second); //saves only children of the node 
     } 

     parse_tree(it->second, nkey + it->first); //recursion 
    } 
} 

Результаты использованием write_xml ("test.html", Pt)

(Мы получаем все дерево, мы хотим только узел)

<node id="A.html"> 
    <subnode> child A1 </subnode> 
    <subnode> child A2 </subnode> 
</node> 
<node id="B.html"> 
    <subnode> child B1 </subnode> 
    <subnode> child B2 </subnode> 
</node> 

Результаты с использованием write_xml ("test.html", it-> второй)

(У нас нет родителей узел .. только дочерние узлы)

<subnode> child B1 </subnode> 
<subnode> child B2 </subnode> 

желаемого результата

(Мы хотим, чтобы узел, и это дети, .. как так)

<node id="B.html"> 
    <subnode> child B1 </subnode> 
    <subnode> child B2 </subnode> 
</node> 

ответ

2

UPDATE 2

переписан в ответ на комментарий/обновленный вопрос.

Существует два способа.

  1. Вы можете использовать недокументированные функции write_xml_element написать один элемент (с помощью ключа в качестве имени элемента):

    // write the single element: (undocumented API) 
        boost::property_tree::xml_parser::write_xml_element(
          std::cout, it->first, it->second, 
          0, settings 
         ); 
    
  2. или вы можете создать новый объект ptree с единственным ребенком

    ptree tmp; 
        tmp.add_child(it->first, it->second); 
        write_xml(std::cout, tmp, settings); 
    

Live On Coliru

#include <boost/property_tree/ptree.hpp> 
#include <boost/property_tree/xml_parser.hpp> 

#include <fstream> 
#include <iostream> 

using namespace boost::property_tree; 


void parse_tree(ptree& pt, std::string key) 
{ 
    std::string nkey; 
    auto settings = xml_parser::xml_writer_make_settings<std::string>('\t', 1); 

    if (!key.empty()) { 
     nkey = key + "."; 
    } 

    ptree::const_iterator end = pt.end(); 
    for(ptree::iterator it = pt.begin(); it != end; ++it) 
    { 
     //if the node's id an .html filname, save the node to file 
     std::string id = it->second.get("<xmlattr>.id",""); 

     if (id.find(key) != std::string::npos) { 
      // write the single element: (undocumented API) 
      boost::property_tree::xml_parser::write_xml_element(
        std::cout, it->first, it->second, 
        0, settings 
       ); 

      // or: create a new pt with the single child 
      std::cout << "\n==========================\n\n"; 
      ptree tmp; 
      tmp.add_child(it->first, it->second); 
      write_xml(std::cout, tmp, settings); 
     } 

     parse_tree(it->second, nkey + it->first); //recursion 
    } 
} 

int main() { 
    ptree pt; 
    read_xml("input.txt", pt); 

    parse_tree(pt, "B"); 
} 

Выход:

<node id="B.html"> 
    <subnode> child B1 </subnode> 
    <subnode> child B2 </subnode> 
</node> 

========================== 

<?xml version="1.0" encoding="utf-8"?> 
<node id="B.html">  
    <subnode> child B1 </subnode> 
    <subnode> child B2 </subnode> 
</node> 
+0

Получение значений не мой вопрос .. мне нужно Ptree текущего itteration .. node.second обеспечивает Ptree дочерних узлов .. I нужен родительский ptree этих дочерних узлов ... Мне нужно что-то вроде 'boost :: property_tree :: ptree MyPtree = node.second.get_parent();' или что-то подобное.Спасибо – aquawicket

+0

Это должен был быть ваш вопрос тогда :) Обновлен ответ. – sehe

+0

жаль, что так расплывчато. Я обновил, чтобы полностью показать, с чем имею дело. И я очень благодарю вас за помощь :) – aquawicket

Смежные вопросы