在Cocos2D Mac中将XML数据加载到文本字段中

时间:2011-03-15 16:02:44

标签: xml cocos2d-iphone

我一直在玩XML,经历一些教程,但我的需求是特定的。想象一下,你有一个CCLabel,并且你想从XML文件中加载数据。因此,在场景x上,您可以从XML的相关部分加载数据。例如,假设您根据场景输入页码。

有没有人有任何例子,或者有人能指出我应该阅读的任何内容吗?

问候。

1 个答案:

答案 0 :(得分:0)

要阅读XML,请查看NSXMLParser指南。由您来管理XML的结构,但实际上,当您从解析器接收读取事件时,使用它所读取的文本应该是微不足道的。

假设您的XML文件类似于:

<scene id=1>
  <label id=1 text="Label Text" />
</scene>
<scene id=2>
  <label id=2 text="Scene 2 Text" />
</scene>

您有几个选择 - 您可以在每次场景加载时解析文件,忽略除id = x(其中x是某种与id相关的场景引用)的内部结构之外的所有内容,或者您​​可以加载应用程序启动时的整个xml并存储它的某种结构。我更喜欢第一种选择。

作为一个基本示例(在我链接到的文档中仍有更好的解释),您的元素阅读功能可能会这样做:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

  if ( [elementName isEqualToString:@"label"]) {
    //attributeDict contains the attributes of the element,
    //in your case, "text" is one of the keys, and "Label Text" would be the value
    //this would pass the specific label text from the xml file to a function in your scene
    [scene someFunctionForPopulatingLabel:[attributeDict objectForKey:@"text"]];
  }

}