最近,是用xml比较多。但是网上的这方面的资料特别少。我就自己弄了个。。使用的是tinyxml类,他具体怎么用可以看我另一篇博文。
我读取的xml是
<?xml version="1.0" encoding="UTF-8"?> <list> <dict id="1" key="english" > <key>english</key> <acceptation>英语;英语语言;英格兰人;(英国)纯正英语; </acceptation> <pos>adj.</pos> <acceptation>英格兰的;英国的;英语的;用英语写的; </acceptation> </dict> <dict id="2" key="one" > <key>one</key> <acceptation>(数字)一;一个;(基数)一,第一; </acceptation> <pos>n.</pos> <acceptation>一个人;一点钟;一体;独一; </acceptation> </dict> <dict id="3" key="key" > <key>key</key> <pos>vt.</pos> <acceptation>键入;锁上;调节…的音调;提供线索;</acceptation> </dict> </list>
char *file = "egxml.xml"; TiXmlDocument xmlDoc(file); xmlDoc.LoadFile(); TiXmlElement* pRootElement = xmlDoc.RootElement(); //获取跟节点 TiXmlElement* pElesele = selectXml(pRootElement,"2","id"); //查找节点 string msg = ""; msg += dumpNode(pElesele,0); //读取该节点所有数据
TiXmlElement* CegDlg::selectXml(TiXmlElement *pRootElement,string strVal,string strName) //跟目录节点,查询属性值,查询属性 { TiXmlElement* pEle = NULL; string msg = ""; TiXmlElement* reEle = NULL; //用于返回 for (pEle = pRootElement->FirstChildElement(); pEle; pEle = pEle->NextSiblingElement()) //循环下面所有节点 { // recursive find sub node return node pointer int t = pEle->Type(); TiXmlElement * pElement = pEle->ToElement(); //转换至节点 TiXmlAttribute * pAttr = pElement->FirstAttribute(); //获取第一个属性 TiXmlAttribute * pNextAttr =NULL; if(pAttr != NULL) { string tmpAttrVal = ""; string tmpAttrName = ""; do { tmpAttrVal = pAttr->Value(); //属性值 tmpAttrName = pAttr->Name(); //属性name if(tmpAttrVal == strVal && tmpAttrName == strName) { return reEle = pElement; //找到就返回当前节点 break; } }while(pAttr = pAttr->Next()); //转移到下一个属性 } } return reEle; }
string CegDlg::dumpNode(TiXmlNode * pNode,int flag) { string msg = ""; if(pNode == NULL) { return ""; } TiXmlText * pText = NULL; TiXmlNode * pChildNode = NULL; int t = pNode->Type(); if(t == TiXmlText::TINYXML_TEXT) //节点类型是text节点 { pText = pNode->ToText(); string text = pText->Value(); if(!text.empty()) { msg = msg + "="+ text; } } else if(t == TiXmlText::TINYXML_ELEMENT) //节点类型是Element { msg = msg + "rn"; int num = flag; while(num >= 1) { msg = msg + "t"; num--; } msg = msg + pNode->Value(); //输出属性 TiXmlElement * pElement = pNode->ToElement(); TiXmlAttribute * pAttr = pElement->FirstAttribute(); TiXmlAttribute * pNextAttr =NULL; string tmpAttrMsg = "["; if(pAttr != NULL) { string tmpAttrVal = ""; string tmpAttrName = ""; do { tmpAttrVal = pAttr->Value(); tmpAttrName = pAttr->Name(); tmpAttrMsg += tmpAttrName+"=" + tmpAttrVal+","; //各个属性之间用逗号分隔 }while(pAttr = pAttr->Next()); tmpAttrMsg = tmpAttrMsg.erase(tmpAttrMsg.find_last_of(",")); } tmpAttrMsg += "]"; msg += tmpAttrMsg; } //循环访问它的每一个元素 for(pChildNode=pNode->FirstChild();pChildNode!=0;pChildNode = pChildNode->NextSibling()) { msg = msg + dumpNode(pChildNode,flag+1); } return msg; }