1. 程式人生 > >tinyxml2對XML檔案的解析初探

tinyxml2對XML檔案的解析初探

今天需要對一個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");
}