先下载TinyXML,百度一下就行,下载下来解压,里面有2个头文件和4个cpp文件,一起加到工程里面,如图所示
http://up.2cto.com/2013/0830/20130830105328361.jpg
xmlTest.cpp是包含主函数的文件,下面直接上代码,很简单,不管怎么样,总算是实现了,虽然题目要求不使用外加类库实现,过段时间等题解出来我再上来更新不加外库实现的方法。
<School name="软件学院">
<Class name = "C++">
<Student name="tinyxml" number="123">
<email>[email protected]</email>
<address>中国</address>
</Student>
<Student name="jsoncpp" number="456">
<email>[email protected].com</email>
<address>美国</address>
</Student>
</Class>
</School>
//以上是要读取xml文件,下面的是xmlTest.cpp。
#include <iostream>
#include "tinystr.h"
#include "tinyxml.h"
#include <string>
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 ;
}
运行结果如下
http://up.2cto.com/2013/0830/20130830105337743.jpg
原文链接:
http://www.2cto.com/kf/201308/239962.html