最近在寫一個小工具時,需要用C++解析XML文件。使用了TinyXML這個精巧的C++庫,使用起來確實比較方便,下面給出如何遍歷一個xml文件的方法,很好用哦,根據自己的需要可以修改該函數,雖然簡單,但是實用。
1 void
2 parseElement( TiXmlNode* pElem )
3 {
4 if ( NULL == pElem )
5 {
6 return;
7 }
8
9 TiXmlNode* pElement = pElem->FirstChild();
10
11 for ( ; pElement; pElement = pElement->NextSibling() )
12 {
13 int nType = pElement->Type();
14
15 switch ( nType )
16 {
17 case TiXmlNode::ELEMENT:
18 parseElement( pElement );
19 if ( 0 == stricmp( pElement->Value(), “Property” ) )
20 {
21 std::string strValue = pElement->ToElement()->Attribute( “Value” );
22 size_t pos = strValue.find( “set” );
23 if ( string::npos != pos )
24 {
25 std::cout << strValue << std::endl;
26 }
27 }
28 break;
29 case TiXmlNode::TEXT:
30 std::cout << pElement << std::endl;
31 break;
32 default:
33 break;
34 }
35 }
36 }
37