• 服务器开发24:tinyxml使用(服务器起服读取配置信息接口)


    一、tinyxml代码介绍

    二、代码使用说明

    1)包裹头文件和动态库引用

    • 1)在stdafx.h头文件中增加头文件引用#include “tinyxml/tinyxml.h”

    • 2)在stdafx.h中加入动态库引用

    #ifdef _DEBUG
    #pragma comment(lib,"TinyXMLD.lib")
    #else
    #pragma comment(lib,"TinyXML.lib")
    #endif
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2)基础操作:读取xml文件

    TiXmlDocument lconfigXML;
    if( !lconfigXML.LoadFile( strXmlFile.c_str() ) )
    {
        break;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3)基础操作:保存xml参数到文本

    TiXmlDocument tyDoc;
    …
    tyDoc.SaveFile(m_strFilePath);
    
    • 1
    • 2
    • 3

    4)增:举例生成xml文件

    • 举例要生成的xml
    <?xml version="1.0" ?> //TiXmlDeclaration,声明
    <MyApp>    //TiXmlElement,元素
        <!-- Settings for MyApp -->//TiXmlComment,注释
        <Messages>//TiXmlElement,元素
            <Welcome>Welcome to MyApp</Welcome>
    //<Welcome>是元素TiXmlElement ,“Welcome to MyApp”是TiXmlText,文本
            <Farewell>Thank you for using MyApp</Farewell>//同上
        </Messages>
        <Windows>//TiXmlElement,元素
            <Window name="MainFrame" x="5" y="15" w="400" h="250" />
    // Window是元素TiXmlElement ,name、x、y、h是TiXmlAttribute
        </Windows>
        <Connection ip="192.168.0.1" timeout="123.456000" />
    </MyApp>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 创建上面xml的代码
    void write_app_settings_doc( )  
    {  
        TiXmlDocument doc;  
        TiXmlElement* msg;
        //1、写声明
        TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );  
        doc.LinkEndChild( decl );   
        
        //2、创建根元素MyApp
        TiXmlElement * root = new TiXmlElement( "MyApp" );  
        doc.LinkEndChild( root );  
    	
    	//3、创建注释-Settings for MyApp
        TiXmlComment * comment = new TiXmlComment();
        comment->SetValue(" Settings for MyApp " );  
        root->LinkEndChild( comment );   
    	
    	//4、在MyApp下面创建Message这个元素
        TiXmlElement * msgs = new TiXmlElement( "Messages" );  
        root->LinkEndChild( msgs );   //注意这是用root调用
    
    	//5、在Message下面创建新元素Welconme
        msg = new TiXmlElement( "Welcome" );  
        msg->LinkEndChild( new TiXmlText( "Welcome to MyApp" ));  
        msgs->LinkEndChild( msg );   
    	
    	//6、在Message下面创建新元素Farewell
        msg = new TiXmlElement( "Farewell" );  
        msg->LinkEndChild( new TiXmlText( "Thank you for using MyApp" ));  
        msgs->LinkEndChild( msg );   
    
    	//7、在root下创建新元素windwos
        TiXmlElement * windows = new TiXmlElement( "Windows" );  
        root->LinkEndChild( windows );  
    
    	//8、填充window
        TiXmlElement * window;
        window = new TiXmlElement( "Window" );  
        windows->LinkEndChild( window );  
        window->SetAttribute("name", "MainFrame");
        window->SetAttribute("x", 5);
        window->SetAttribute("y", 15);
        window->SetAttribute("w", 400);
        window->SetAttribute("h", 250);
    
    	//9、在root下创建connection这个元素
        TiXmlElement * cxn = new TiXmlElement( "Connection" );  
        root->LinkEndChild( cxn );  
        cxn->SetAttribute("ip", "192.168.0.1");
        cxn->SetDoubleAttribute("timeout", 123.456); // floating point attrib
        dump_to_stdout( &doc );
        doc.SaveFile( "appsettings.xml" );  
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    5)改:修改节点值

    • 查找内容为,现需要将1234改成其他值
    TiXmlNode* lpnode = NULL;
    lpnode = tixml.RootElement()->IterateChildren("mfid",lpnode);
    TiXmlAttribute* tiattr = lpnode->ToElement()->FirstAttribute();
    //找到mfid节点,获取第一个属性值。注意,如果有多个属性值,需要判断哪个属性值是需要的
    tiattr->SetValue(mfid.c_str());
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 替换一个节点
    TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ); 
    
    • 1

    6)查:寻找某个节点(返回字符串)\遍历节点或节点的属性

    • 获取link节点
    const TiXmlNode* lpItemNode = NULL;//初始化
    lpItemNode = lconfigXML.RootElement()->IterateChildren("link", lpItemNode);
    if (lpItemNode == NULL)
    {
        //Can not find break;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 获取link节点中的type属性值(返回字符串)
    std::string strType = lpItemNode->ToElement()->Attribute("type");
    
    • 1
    • 遍历节点
    const TiXmlNode* lpMapNode = NULL; //初始化
    lpMapNode = lconfigXML.RootElement()->IterateChildren("node", lpMapNode);
    if (lpMapNode) 
    {
        rms::CStationMapping litem;
        const TiXmlNode* lpItemNode = NULL ;
        while(lpItemNode = lpMapNode->IterateChildren("item",lpItemNode))
        {
            string str = lpItemNode->ToElement()->Attribute("ABC"); 
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 遍历元素属性
    TiXmlAttribute* pAttr = NULL; 
    for (pAttr = pNode->FirstAttribute(); pAttr; pAttr = pAttr->Next())  
    {    
      …
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 节点的下一个兄弟节点
    const TiXmlNode* NextSibling() const;
    
    • 1
    • 元素的下一个元素
    const TiXmlElement* NextSiblingElement() const;
    
    • 1
    • 属性的下一个属性
    const TiXmlAttribute* Next() const;
    
    • 1

    返回值为NULL表示不存在

    7)删:删除节点信息

    • 备注

    TiXmlNode是TiXmlElement、TiXmlComment、TiXmlText、TiXmlDeclaration、TiXmlUnknown、TiXmlDocument的基类

    TiXmlNode node;
    node.Clear();
    
    • 1
    • 2
    • 从A节点上移除子节点B
    TiXmlNode nodeA;
    nodeA. RemoveChild( TiXmlNode* removeThis );
    
    • 1
    • 2
    • 从元素A上移除名字为B的属性
    TiXmlAttribute attrA;
    attrA. RemoveAttribute( const char * name );
    
    • 1
    • 2

    三、整体代码举例

    1)基础类举例

    #include 
    #include 
    using namespace std;
    
    typedef std::map<std::string,std::string> MessageMap;
    
    // a basic window abstraction - demo purposes only
    class WindowSettings
    {
    public:
    	int x,y,w,h;
    	string name;
    
    	WindowSettings()
    		: x(0), y(0), w(100), h(100), name("Untitled")
    	{
    	}
    
    	WindowSettings(int x, int y, int w, int h, const string& name)
    	{
    		this->x=x;
    		this->y=y;
    		this->w=w;
    		this->h=h;
    		this->name=name;
    	}
    };
    
    class ConnectionSettings
    {
    public:
    	string ip;
    	double timeout;
    };
    
    class AppSettings
    {
    public:
    	string m_name;
    	MessageMap m_messages;
    	list<WindowSettings> m_windows;
    	ConnectionSettings m_connection;
    
    	AppSettings() {}
    
    	void save(const char* pFilename);
    	void load(const char* pFilename);
    	
    	// just to show how to do it
    	void setDemoValues()
    	{
    		m_name="MyApp";
    		m_messages.clear();
    		m_messages["Welcome"]="Welcome to "+m_name;
    		m_messages["Farewell"]="Thank you for using "+m_name;
    		m_windows.clear();
    		m_windows.push_back(WindowSettings(15,15,400,250,"Main"));
    		m_connection.ip="Unknown";
    		m_connection.timeout=123.456;
    	}
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

    2)实际操作xml函数(加载)

    void AppSettings::load(const char* pFilename)
    {
        TiXmlDocument doc(pFilename);
        if (!doc.LoadFile()) return;
    
        TiXmlHandle hDoc(&doc);
        TiXmlElement* pElem;
        TiXmlHandle hRoot(0);
    
        // block: name
        {
            pElem=hDoc.FirstChildElement().Element();
            // should always have a valid root but handle gracefully if it does
            if (!pElem) return;
            m_name=pElem->Value();
    
            // save this for later
            hRoot=TiXmlHandle(pElem);
        }
    
        // block: string table
        {
            m_messages.clear(); // trash existing table
    
            pElem=hRoot.FirstChild( "Messages" ).FirstChild().Element();
            for( pElem; pElem; pElem=pElem->NextSiblingElement())
            {
                const char *pKey=pElem->Value();
                const char *pText=pElem->GetText();
                if (pKey && pText) 
                {
                    m_messages[pKey]=pText;
                }
            }
        }
    
        // block: windows
        {
            m_windows.clear(); // trash existing list
    
            TiXmlElement* pWindowNode=hRoot.FirstChild( "Windows" ).FirstChild().Element();
            for( pWindowNode; pWindowNode; pWindowNode=pWindowNode->NextSiblingElement())
            {
                WindowSettings w;
                const char *pName=pWindowNode->Attribute("name");
                if (pName) w.name=pName;
                
                pWindowNode->QueryIntAttribute("x", &w.x); // If this fails, original value is left as-is
                pWindowNode->QueryIntAttribute("y", &w.y);
                pWindowNode->QueryIntAttribute("w", &w.w);
                pWindowNode->QueryIntAttribute("hh", &w.h);
    
                m_windows.push_back(w);
            }
        }
    
        // block: connection
        {
            pElem=hRoot.FirstChild("Connection").Element();
            if (pElem)
            {
                m_connection.ip=pElem->Attribute("ip");
                pElem->QueryDoubleAttribute("timeout",&m_connection.timeout);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

    3)保存某个xml(save)

    void AppSettings::save(const char* pFilename)
    {
    	TiXmlDocument doc;  
    	TiXmlElement* msg;
    	TiXmlComment * comment;
    	string s;
     	TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );  
    	doc.LinkEndChild( decl ); 
     
    	TiXmlElement * root = new TiXmlElement(m_name.c_str());  
    	doc.LinkEndChild( root );  
    
    	comment = new TiXmlComment();
    	s=" Settings for "+m_name+" ";
    	comment->SetValue(s.c_str());  
    	root->LinkEndChild( comment );  
    
    	// block: messages
    	{
    		MessageMap::iterator iter;
    
    		TiXmlElement * msgs = new TiXmlElement( "Messages" );  
    		root->LinkEndChild( msgs );  
     
    		for (iter=m_messages.begin(); iter != m_messages.end(); iter++)
    		{
    			const string & key=(*iter).first;
    			const string & value=(*iter).second;
    			msg = new TiXmlElement(key.c_str());  
    			msg->LinkEndChild( new TiXmlText(value.c_str()));  
    			msgs->LinkEndChild( msg );  
    		}
    	}
    
    	// block: windows
    	{
    		TiXmlElement * windowsNode = new TiXmlElement( "Windows" );  
    		root->LinkEndChild( windowsNode );  
    
    		list<WindowSettings>::iterator iter;
    
    		for (iter=m_windows.begin(); iter != m_windows.end(); iter++)
    		{
    			const WindowSettings& w=*iter;
    
    			TiXmlElement * window;
    			window = new TiXmlElement( "Window" );  
    			windowsNode->LinkEndChild( window );  
    			window->SetAttribute("name", w.name.c_str());
    			window->SetAttribute("x", w.x);
    			window->SetAttribute("y", w.y);
    			window->SetAttribute("w", w.w);
    			window->SetAttribute("h", w.h);
    		}
    	}
    
    	// block: connection
    	{
    		TiXmlElement * cxn = new TiXmlElement( "Connection" );  
    		root->LinkEndChild( cxn );  
    		cxn->SetAttribute("ip", m_connection.ip.c_str());
    		cxn->SetDoubleAttribute("timeout", m_connection.timeout); 
    	}
    
    	doc.SaveFile(pFilename);  
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
  • 相关阅读:
    java基础1
    Python字典基础与高级详解
    邮件群发软件
    【C++】鱼的一生, 智能指针的实现
    环形单链表问题
    面试题——RabbitMQ
    踩坑——Doris,Can‘t get Kerberos realm, cause by: Can‘t get Kerberos realm
    Stable Diffusion 动画animatediff-cli-prompt-travel
    yolo增加MPDIoU loss
    Redis的神奇之处:为什么它如此快速?【redis第三部分】
  • 原文地址:https://blog.csdn.net/weixin_43679037/article/details/126472239