【问题标题】:How to read and parse an .xml file如何读取和解析 .xml 文件
【发布时间】:2011-04-01 17:10:53
【问题描述】:

我只需要读取一个 .xml 文件;像这样:

<exchanges>
    <exchange>
        <timestamp>2010-08-19 17:15:56</timestamp>
        <userid>Elijah-Woods-MacBook-Pro.local</userid>
        <clientname>elijah</clientname>
        <botid>Jarvis</botid>
        <input>firsthello</input>
        <response>Hello, sir. How may I help you?</response>
    </exchange>
</exchanges>

然后,解析“响应”标签之间的任何内容。

以利亚

【问题讨论】:

    标签: objective-c xml xml-parsing


    【解决方案1】:

    基本思路,代码不完整..基于GDataXML

    http://code.google.com/p/gdata-objectivec-client/source/browse/trunk/Source/XMLSupport/

    另见此对多个解析器的分析

    http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project

    NSArray *entries = [doc nodesForXPath:@"//exchanges/exchange" error:nil];
    for (GDataXMLElement *entry in entries) {
        NSMutableDictionary * dict = [[[NSMutableDictionary alloc]initWithCapacity:7 ] autorelease];
        [dict setValue:[[[entry elementsForName:@"timestamp"] objectAtIndex:0] stringValue] forKey:@"timestamp"];
        [dict setValue:[[[entry elementsForName:@"userid"] objectAtIndex:0] stringValue] forKey:@"userid"];
        [dict setValue:[[[entry elementsForName:@"clientname"] objectAtIndex:0] stringValue] forKey:@"clientname"];
        [dict setValue:[[[entry elementsForName:@"botid"] objectAtIndex:0] stringValue] forKey:@"botid"];
        [dict setValue:[[[entry elementsForName:@"input"] objectAtIndex:0] stringValue] forKey:@"input"];
        [dict setValue:[[[entry elementsForName:@"response"] objectAtIndex:0] stringValue] forKey:@"response"];
    
    }
    

    【讨论】:

      【解决方案2】:

      在 Cocoa 中解析 XML 有两种选择:

      1. Event-Driven,解析器在其中发出您的委托类响应的事件。
      2. Tree-Based,解析器在其中构建您可以查询或修改的 XML 树。

      事件驱动的解析占用较少的内存,但是由于您没有构建一棵完整的 XML 树,因此您不能使用 XPath 或 XQuery 来获取有关文档的信息。基于树通常使用更多内存(因为整个 XML 文档被转换为对象形式并存储在内存中),但它提供了更强大的机制来从树中获取数据。

      【讨论】:

      • 你能展示一个简单的例子来解析这个并得到响应标签之间的内容吗?这就是我所需要的。
      • 这个 .XML 文件位于我的桌面上。
      【解决方案3】:

      TouchXML 也是 iPhone 上一个非常好的 XML 库。它也被证明是解析速度最快的方法之一。

      这是一个示例项目:http://dblog.com.au/general/iphone-sdk-tutorial-building-an-advanced-rss-reader-using-touchxml-part-1/

      如果你有好的“touchxml iphone 教程”,网上还有很多

      【讨论】:

      • 我主要在 Mac 上使用它。 Mac 有没有类似的东西?
      • TouchXML 只是 Cocoa 的 NSXML* 类的替代品(iPhone 上不存在 NSXML*)。
      猜你喜欢
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      相关资源
      最近更新 更多