2012-07-09 49 views
2

如何使用元素和属性的基于范围的循环来做这种工作?基于循环实现的基于循环实现的C++中的XML元素类11

#include <list> 
#include "XMLAttribute.h" 

namespace XML 
{ 
    class Element 
    { 
     private: 
      typedef std::list<Attribute> attribute_container; 
      typedef std::list<Element> element_container; 

     public: 
      XMLElement(); 

      bool has_attributes() const; 
      bool has_elements() const; 
      bool has_data() const; 

      const std::string &name() const; 
      const std::string &data() const; 

     private: 
      std::string _name; 
      std::string _data; 

      attribute_container _attributes; 
      element_container _elements; 
    }; 
} 

我想能够使用这样的:

for (XML::Element &el : element) { .. } 
for (XML::Attribute &at : element) { .. } 

并阻止类似for (auto &some_name : element) { .. } //XML::Element or XML::Attribute?

像这样实现它还是应该改变我的设计?

回答

5

正确的答案是给Element节点函数返回子属性和元素的范围。因此,你可以这样做:

for(auto &element : element.child_elements()) {...} 
for(auto &attribute : element.attributes()) {...} 

child_elements函数将返回某种存储两个迭代器,像一个boost::iterator_range类型。 attributes同样会返回属性元素的范围。

+0

精彩回答!谢谢! – 2012-07-09 18:16:13