今天需要对一个xml文件进行解析,网度了下,使用tinyxml2进行处理,该API中封装了较完备的解析处理类,话不多说,正题如下:
1.从官网下载 tinyxml2的API https://github.com/leethomason/tinyxml2 注意下载的版本,我下载时为 tinyxml2-master.zip 的压缩包,将里面的 tinyxml2.h与tinyxml2.cpp文件导入项目中,即可完成API的导入
2.实例,解析如图Student.xml文件
<?xml version="1.0" encoding="gb2312"?>
<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>
编码格式为 gb2312是为了能在控制台输出中文不乱码
XmlParseExample.cpp的编码如下:
void main() {
XMLDocument *myDocument = new XMLDocument();
myDocument->LoadFile("Students.xml");
XMLElement* rootElement = myDocument->RootElement(); //Class
XMLElement* firstElement = rootElement->FirstChildElement(); //Students
XMLElement* secondElement = firstElement->FirstChildElement(); //Students
while (secondElement) {
const XMLAttribute* attributeOfStudent = secondElement->FirstAttribute(); //获得student的name属性
while (attributeOfStudent) {
std::cout << attributeOfStudent->Name() << " : " << attributeOfStudent->Value() << std::endl;
attributeOfStudent = attributeOfStudent->Next();
}
XMLElement* Element = secondElement->FirstChildElement();//获得student的phone元素
while (Element)
{
std::cout << Element->Name() << " : " << Element->GetText() << std::endl;
Element = Element->NextSiblingElement();
}
secondElement = secondElement->NextSiblingElement();
}
system("pause");
}