您的位置:首页 > 其它

XML的简单学习(一个优秀的mini库…

2014-06-25 13:21 316 查看
废话也不多说了,不懂XML的可以先看一下DOM,这里不再复述。
直入主题:
分为两种方法:

第一种方法:定义属性Attribute
首先,看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());

}

}

节点元素则比较容易理解,但是调用和配置文件中写起来比较麻烦,各自所需嘛。
错误之处,还望指出谢谢!
如需转载,请注明出处http://blog.sina.com.cn/s/blog_9abbd7920101a80w.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: