今天背考研单词,感觉可以自己做一个小小单词本,所以就想办法弄词库,在网上一搜发现,有xml版本的新东方考研词汇的单词库,所以就想着写个xml解析类的单词本。
今天在网上看了下各种xml文件解析的库,感觉TinyXML类库还可以,所以就下载下来打算试试,一试果然挺好用的,这就解决写这个程序了第一步——解析XML文件。
这是本人上传的6个类库,和开发文档,类库直接导入工程中然后应用相应的头文件即可,地址:http://download.csdn.net/detail/iaccepted/5298810。
例子如下:
#include "tinyxml.h" #include <iostream> #include <string> using namespace std; int main() { TiXmlDocument* myDocument = new TiXmlDocument(); myDocument->LoadFile("Students.xml"); TiXmlElement* rootElement = myDocument->RootElement(); //Class TiXmlElement* studentsElement = rootElement->FirstChildElement(); //Students TiXmlElement* studentElement = studentsElement->FirstChildElement(); //Student while ( studentElement ) { TiXmlAttribute* attributeOfStudent = studentElement->FirstAttribute(); //获得student的name属性 while ( attributeOfStudent ) { std::cout << attributeOfStudent->Name() << " : " << attributeOfStudent->Value() << std::endl; attributeOfStudent = attributeOfStudent->Next(); } TiXmlElement* phoneElement = studentElement->FirstChildElement();//获得student的phone元素 std::cout << "phone" << " : " << phoneElement->GetText() << std::endl; TiXmlElement* addressElement = phoneElement->NextSiblingElement(); std::cout << "address" << " : " << phoneElement->GetText() << std::endl; studentElement = studentElement->NextSiblingElement(); } return 0; }
自己接着就写了个解析单词的例子:
<wordbook> <item> <word>gradual</word> <trans>a.逐渐的,逐步的</trans> </item> <item> <word>deceive</word> <trans>v.欺骗,蒙蔽</trans> </item> </wordbook>
程序:
#include "tinyxml.h" #include <iostream> #include <string> using namespace std; int main() { TiXmlDocument* myDocument = new TiXmlDocument(); myDocument->LoadFile("words.xml"); TiXmlElement* wordbook = myDocument->RootElement(); //wordbook TiXmlElement* items = wordbook->FirstChildElement();//item while ( items ) { TiXmlElement* word = items->FirstChildElement(); std::cout << word->GetText() << std::endl; TiXmlElement* trans = word->NextSiblingElement(); std::cout << trans->GetText() << std::endl; items = items->NextSiblingElement(); } return 0; }
以上例子完全通过测试,所以,感觉这个类库很好用的,呵呵