先
下载TinyXML,百度一下就行,下载下来解压,里面有2个头文件和4个cpp文件,一起加到工程里面,如图所示
xmlTest.cpp是包含主函数的文件,下面直接上代码,很简单,不管怎么样,总算是实现了,虽然题目要求不使用外加类库实现,过段时间等题解出来我再上来更新不加外库实现的方法。
tinyxml@163.com 中国jsoncpp@gmail.com 美国
以上是要读取xml文件,下面的是xmlTest.cpp。
#include#include "tinystr.h" #include "tinyxml.h" #include using namespace std; void readSchoolXml() { using namespace std; const char * xmlFile = "school.xml"; TiXmlDocument doc; if (doc.LoadFile(xmlFile)) { doc.Print(); } else { cout << "can not parse school.xml" << endl; return; } TiXmlElement* rootElement = doc.RootElement(); //School元素 TiXmlElement* classElement = rootElement-> FirstChildElement(); // Class元素 TiXmlElement* studentElement = classElement->FirstChildElement(); //Students for (; studentElement != NULL; studentElement = studentElement->NextSiblingElement() ) { TiXmlAttribute* attributeOfStudent = studentElement->FirstAttribute(); //获得student的name属性 for (;attributeOfStudent != NULL; attributeOfStudent = attributeOfStudent->Next() ) { cout << attributeOfStudent->Name() << " : " << attributeOfStudent->Value() << std::endl; } TiXmlElement* studentContactElement = studentElement->FirstChildElement();//获得student的第一个联系方式 for (; studentContactElement != NULL; studentContactElement = studentContactElement->NextSiblingElement() ) { string contactType = studentContactElement->Value(); string contactValue = studentContactElement->GetText(); cout << contactType << " : " << contactValue << std::endl; } } } int main(){ readSchoolXml(); system("pause"); return 1; }
运行结果界面: