废话也不多说了,不懂XML的可以先看一下DOM,这里不再复述。
直入主题:
分为两种方法:
首先,看test.xml
- <Root>
<Textures> - <Texture px="456" py="312" lx="320" ly="200" ap="1"/>
</Textures> - </Root>
C++文件中的运行:
在head中先定义一个数组:float testPicture_[5];
在cpp中:
- void TiXml()
- {
- TiXmlDocument doc("test.xml");//定义test.xml文件
- bool loadOk = doc.LoadFile();//获取
- if (!loadOk)
- {
- printf("load false!");
- exit(-1);
- }
- TiXmlElement* rootElement = doc.FirstChildElement("Root");//root
- TiXmlElement* texturesElement = rootElement->FirstChildElement("Textures");//Textures
- TiXmlAttribute* attrOfTexture = texturesElement->FirstChildElement()->FirstAttribute();//获得Texture的px属性
- while(attrOfTexture)//在Texture的属性中循环,否则跳出
- {
- for (int i = 0; i<5; ++i)
- {
- testPicture_[i] = atof(attrOfTexture->Value());//获取相应属性值
- attrOfTexture = attrOfTexture->Next();//切换至下一个属性
- printf("%.2f\n",testPicture_[i]);//输出标记
- }
- }
- }
首先是test.xml
- <Root>
<Textures> - <positionX>456</positionX>
- <positionY>312</positionY>
- <lengthX>320</lengthX>
- <lengthY>200</lengthY>
- <alpha>1</alpha>
</Textures> - </Root>
然后一样在head中定义数组:
float
testPicture_[5];
在cpp中:
- void TiXml()
- {
- TiXmlDocument doc("test.xml");
- bool loadOk = doc.LoadFile();
- if (!loadOk)
- {
- printf("load false!");
- exit(-1);
- }
- TiXmlElement* rootElement = doc.FirstChildElement("Root");//root
- TiXmlElement* texturesElement = rootElement->FirstChildElement("Textures");//Textures
- if(texturesElement)
- {
- testPicture_[0]
= atof(texturesElement->FirstChildElement("positionX")->GetText()); testPicture_[1] = atof(texturesElement->FirstChildElement("positionY")->GetText()); testPicture_[2] = atof(texturesElement->FirstChildElement("lengthX")->GetText()); testPicture_[3] = atof(texturesElement->FirstChildElement("lengthY")->GetText()); testPicture_[4] = atof(texturesElement->FirstChildElement("alpha")->GetText()); - }
- }
错误之处,还望指出谢谢!