CMarkup读取xml文件简单使用

 1 class CClassXmlGet
 2 {
 3 public:
 4     CClassXmlGet(void);
 5     ~CClassXmlGet();
 6     /***********************************/
 7     bool InitXmlInfo(std::string strLoadPath);
 8     std::string GetUserName();
 9     std::string GetPassWord();
10 private:
11     std::map<std::string,std::string>m_mapXml;
12     std::string m_strUserName;
13     std::string m_strPassWord;
14 };
 1 #include "ClassXmlGet.h"
 2 #include "Markup.h"
 3 
 4 CClassXmlGet::CClassXmlGet(void)
 5 {
 6     m_mapXml.clear();
 7     m_strUserName = "";
 8     m_strPassWord = "";
 9 }
10 CClassXmlGet::~CClassXmlGet()
11 {
12     m_mapXml.clear();
13     m_strUserName = "";
14     m_strPassWord = "";
15 }
16 
17 bool CClassXmlGet::InitXmlInfo(std::string strLoadPath)
18 {
19     std::string strTempPath = strLoadPath + "conf/config_item.xml";//具体的文件路径+文件名
20     CMarkup initXML;
21     if (!initXML.Load(strTempPath.c_str())){
22         return false;
23     }
24     if (!initXML.FindElem("config") || !initXML.IntoElem()){
25         return false;
26     }
27     while(initXML.FindElem("item")){
28         std::string strkey = initXML.GetAttrib("key");
29         std::string strvalue = initXML.GetAttrib("value");
30         m_mapXml[strkey] = strvalue;
31     }
32     return true;
33 }
34 std::string CClassXmlGet::GetUserName()
35 {
36     if(!m_strUserName.empty())
37         return m_strUserName;
38 
39     std::map<std::string,std::string>::const_iterator constItor = m_mapXml.find("ServerUserName");
40     if(constItor != m_mapXml.end())
41         m_strUserName = constItor->second;
42 
43     return m_strUserName;
44 }
45 std::string CClassXmlGet::GetPassWord()
46 {
47     if(!m_strPassWord.empty())
48         return m_strPassWord;
49 
50     std::map<std::string,std::string>::const_iterator constItor = m_mapXml.find("ServerPass");
51     if(constItor != m_mapXml.end())
52         m_strPassWord = constItor->second;
53 
54     return m_strPassWord;
55 }

具体的xml文档结构

1 <?xml version="1.0" encoding="UTF-8" ?>
2 <config>
3     <item key="ServerPass" value="12345">
4         <cap id="Test1" />
5     </item>
6     <item key="ServerUserName"  value="admin">
7         <cap id="test2" />
8     </item>
9 </config>

核心思想:

当遇到的xml文件节点名称都一样,例如都是item作为节点名称,不同的是item节点中包含的内容不一样时,可以采取将全部节点内容读出来,放到一个map表中,根据map表中的key值进行获取

posted @ 2023-04-26 08:54  冥天笑  阅读(105)  评论(0编辑  收藏  举报