DALXmlFile.h:
#ifndef DALXMLFILE_H_INCLUDED
#define DALXMLFILE_H_INCLUDED
#include "rapidxml.hpp"
#include "rapidxml_utils.hpp"
#include "rapidxml_print.hpp"
///a wrapper for xml file.
class DALXmlFile
{
public:
DALXmlFile();
~DALXmlFile();
/**
get a node by the _key. _key is the node's name, the function will return
the node contain the name.
*/
static rapidxml::xml_node<>* get_xml_node(rapidxml::xml_node<>* _node,
const char* _key);
///get attribute value by searching the _key in _curNodePtr refrence to the node.
static std::string get_xml_attr(rapidxml::xml_node<>* _node,
const char* _key);
///get all attribute of the node
static void get_attr_of_node(rapidxml::xml_node<>* _node,
hash_key& _attrs);
///return the first level node of the xml document.
rapidxml::xml_node<>* root();
private:
rapidxml::file<> fdoc;
rapidxml::xml_document<> doc;
};
#endif
DALXmlFile.cpp:
#include "DALXmlFile.h"
///initialize xml.
DALXmlFile::DALXmlFile():fdoc(config_path.c_str())
{
doc.parse<0>(fdoc.data());
}
DALXmlFile::~DALXmlFile()
{
}
/// search _key in the _curNodePtr tree and return the relative sub tree.
rapidxml::xml_node<>* DALXmlFile::get_xml_node( rapidxml::xml_node<>* _node, const char* _key )
{
_node = _node->first_node();
while(_node)
{
if(!strncmp(lower(_node->name()),_key, DAL_CONFIG_NODE_MAX_LENGTH))
return _node;
_node = _node->next_sibling();
}
throw DALException(DAL_ERROR_XML_NODE_NOT_EXIST, string("node is ") + _key);
}
///search _key in the _curNodePtr node and return the relative attribute.
string DALXmlFile::get_xml_attr(rapidxml::xml_node<>* _node, const char* _key)
{
xml_attribute<>* ptr = _node->first_attribute();
string tmp;
while(ptr)
{
if(!strncmp(lower(ptr->name()),_key, DAL_CONFIG_NODE_MAX_LENGTH))
{
if(ptr->value())
{
tmp = ptr->value();
}
return tmp;
}
ptr = ptr->next_attribute();
}
throw DALException(DAL_ERROR_XML_ATTR_NOT_EXIST, string(" attr is ") \
+ _key);
}
void DALXmlFile::get_attr_of_node(rapidxml::xml_node<>* _node,
hash_key& _attrs)
{
xml_attribute<>* ptr = _node->first_attribute();
while(ptr)
{
if(ptr->value())
{
_attrs[lower(ptr->name())] = ptr->value();
}
ptr = ptr->next_attribute();
}
}
xml_node<>* DALXmlFile::root()
{
return doc.first_node();
}
rapidxml的简单封装
最新推荐文章于 2018-07-11 21:28:20 发布