<Class name="计算机软件班">
<Students>
<student name="张三" studentNo="13031001" sex="男" age="22">
<phone>88208888</phone>
<address>西安市太白南路二号</address>
</student>
<student name="李四" studentNo="13031002" sex="男" age="20">
<phone>88206666</phone>
<address>西安市光华路</address>
</student>
</Students>
</Class>
解析程序如下:
#pragma comment("tinyxml_STL.lib", lib)
#include <iostream>
#include "tinyxml.h"
#include "tinystr.h"
using namespace std;
int main()
{
TiXmlDocument xml("hkx.xml");
xml.LoadFile();
xml.Print();
std::cout<<std::endl;
TiXmlElement* rootElement = xml.RootElement();
TiXmlAttribute* rootAttribute = rootElement->FirstAttribute();
while (rootAttribute)
{
cout<<rootAttribute->Name()<<":"<<rootAttribute->Value()<<endl;
rootAttribute = rootAttribute->Next();
}
TiXmlElement* studentsElement = rootElement->FirstChildElement();
TiXmlElement* studentElement = studentsElement->FirstChildElement();
while (studentElement)
{
TiXmlAttribute* attribute = studentElement->FirstAttribute();
while (attribute)
{
cout<<attribute->Name()<<":"<<attribute->Value()<<endl;
attribute = attribute->Next();
}
TiXmlElement* phoneElement = studentElement->FirstChildElement();
cout<<phoneElement->GetText()<<endl;
TiXmlElement* addressElement = phoneElement->NextSiblingElement();
cout<<addressElement->GetText()<<endl;
studentElement = studentElement->NextSiblingElement();
}
return 0;
}
解析xml字符串流:
int main()
{
string xmlString =
"<Class name=\"计算机软件班\">\
<Students>\
<student name=\"张三\" studentNo=\"13031001\" sex=\"男\" age=\"22\">\
<phone>88208888</phone>\
<address>西安市太白南路二号</address>\
</student>\
<student name=\"李四\" studentNo=\"13031002\" sex=\"男\" age=\"20\">\
<phone>88206666</phone>\
<address>西安市光华路</address>\
</student>\
</Students>\
</Class>";
TiXmlDocument* xml = new TiXmlDocument();
xml->Parse(xmlString.c_str());
xml->Print();
TiXmlElement* rootElement = xml->RootElement();
TiXmlAttribute* rootAttribute = rootElement->FirstAttribute();
while (rootAttribute)
{
cout<<rootAttribute->Name()<<":"<<rootAttribute->Value()<<endl;
rootAttribute = rootAttribute->Next();
}
TiXmlElement* studentsElement = rootElement->FirstChildElement();
TiXmlElement* studentElement = studentsElement->FirstChildElement();
while (studentElement)
{
TiXmlAttribute* attribute = studentElement->FirstAttribute();
while (attribute)
{
cout<<attribute->Name()<<":"<<attribute->Value()<<endl;
attribute = attribute->Next();
}
TiXmlElement* phoneElement = studentElement->FirstChildElement();
cout<<phoneElement->GetText()<<endl;
TiXmlElement* addressElement = phoneElement->NextSiblingElement();
cout<<addressElement->GetText()<<endl;
studentElement = studentElement->NextSiblingElement();
}
return 0;
}
tinyXML的一些类:
TiXmlBase:整个TinyXML模型的基类。
TiXmlHandler:定义了针对XML的一些操作。