rapidxml的簡單封裝

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();
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章