加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:39:07 所属栏目:百科 来源:网络整理
导读:废话也不多说了,不懂XML的可以先看一下DOM,这里不再复述。 直入主题: 分为两种方法: 第一种方法:定义属性Attribute 首先,看test.xml Root Textures Texture px="456" py="312" lx="320" ly="200" ap="1"/ /Textures /Root C++文件中的运行: 在head中
废话也不多说了,不懂XML的可以先看一下DOM,这里不再复述。
直入主题:
分为两种方法:

第一种方法:定义属性Attribute
首先,看test.xml
  1. <Root>
  2. <Textures>
  3. <Texture px="456" py="312" lx="320" ly="200" ap="1"/>
  4. </Textures>
  5. </Root>

C++文件中的运行:
在head中先定义一个数组:float testPicture_[5];
在cpp中:
  1. void TiXml()
  2. {
  3. TiXmlDocument doc("test.xml");//定义test.xml文件

  4. bool loadOk = doc.LoadFile();//获取
  5. if (!loadOk)
  6. {
  7. printf("load false!");
  8. exit(-1);
  9. }

  10. TiXmlElement* rootElement = doc.FirstChildElement("Root");//root
  11. TiXmlElement* texturesElement = rootElement->FirstChildElement("Textures");//Textures
  12. TiXmlAttribute* attrOfTexture = texturesElement->FirstChildElement()->FirstAttribute();//获得Texture的px属性

  13. while(attrOfTexture)//在Texture的属性中循环,否则跳出
  14. {
  15. for (int i = 0; i<5; ++i)
  16. {
  17. testPicture_[i] = atof(attrOfTexture->Value());//获取相应属性值
  18. attrOfTexture = attrOfTexture->Next();//切换至下一个属性
  19. printf("%.2fn",testPicture_[i]);//输出标记
  20. }
  21. }

第二种方法:直接定义节点元素方法
首先是test.xml
  1. <Root>
  2. <Textures>
  3. <positionX>456</positionX>
  4. <positionY>312</positionY>
  5. <lengthX>320</lengthX>
  6. <lengthY>200</lengthY>
  7. <alpha>1</alpha>
  8. </Textures>
  9. </Root>

然后一样在head中定义数组: float testPicture_[5];
在cpp中:
  1. void TiXml()
  2. {
  3. TiXmlDocument doc("test.xml");

  4. bool loadOk = doc.LoadFile();
  5. if (!loadOk)
  6. {
  7. printf("load false!");
  8. exit(-1);
  9. }

  10. TiXmlElement* rootElement = doc.FirstChildElement("Root");//root
  11. TiXmlElement* texturesElement = rootElement->FirstChildElement("Textures");//Textures
  12. if(texturesElement)
  13. {
  14. testPicture_[0]= atof(texturesElement->FirstChildElement("positionX")->GetText());
  15. testPicture_[1]= atof(texturesElement->FirstChildElement("positionY")->GetText());
  16. testPicture_[2]= atof(texturesElement->FirstChildElement("lengthX")->GetText());
  17. testPicture_[3]= atof(texturesElement->FirstChildElement("lengthY")->GetText());
  18. testPicture_[4]= atof(texturesElement->FirstChildElement("alpha")->GetText());
  19. }
  20. }

节点元素则比较容易理解,但是调用和配置文件中写起来比较麻烦,各自所需嘛。
错误之处,还望指出谢谢!
如需转载,请注明出处 http://blog.sina.com.cn/s/blog_9abbd7920101a80w.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读