首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用objective C读取XML文件(iOS 5)

使用objective C读取XML文件(iOS 5)
EN

Stack Overflow用户
提问于 2012-06-27 18:16:03
回答 2查看 2.5K关注 0票数 0

我正在尝试使用objective C语言读取XML文件并对其进行解析。我正在使用XCode 4.2并为iPhone编写应用程序。我已经创建了视图控制器.h和.m文件。我正在使用NSXMLParser和xml文件被命名为"simple.xml“。我已经从w3schools网站上下载了。我没有使用ARC。没有生成错误。下面是我在viewDidLoad方法中的代码-

代码语言:javascript
复制
NSString *filePath;
filePath = [[NSBundle mainBundle] pathForResource:@"simple" ofType:@"xml"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath]; 
NSString *urlString = [[NSString alloc] initWithData:fileData encoding:NSASCIIStringEncoding];
NSLog(@"File data is %@",urlString);    
NSString* str= urlString;
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
xmlParser = [[NSXMLParser alloc] initWithData:data];
xmlParser.delegate = self;
[xmlParser parse];

以下是XML内容-

代码语言:javascript
复制
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<breakfast_menu>
    <food>
        <name>Belgian Waffles</name>
        <price>$5.95</price>
        <description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
        <calories>650</calories>
    </food>
    <food>
        <name>Strawberry Belgian Waffles</name>
        <price>$7.95</price>
        <description>light Belgian waffles covered with strawberries and whipped cream</description>
        <calories>900</calories>
    </food>
    <food>
        <name>Berry-Berry Belgian Waffles</name>
        <price>$8.95</price>
        <description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
        <calories>900</calories>
    </food> 
  </breakfast_menu>

但是当我执行这段代码时,程序突然终止了。我在日志中看不到任何异常信息。但它与线程变量有关,因为在XCode中,我使用此变量的行将以绿色显示,并带有文本“fileData 1 stopped executing...”。也许XML是以ISO-8859-1编码的,而我使用的是ASCII编码?早些时候,我使用类似的代码解析从web服务返回的XML,当时响应是用UTF-8编码的。或者也许我在内存management..allos,释放等方面犯了一些错误?在这方面请帮帮我。

我也试着在"TextEdit“中用"UTF-8”来保存文件,但是没有这样的选项。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-06-30 19:42:55

删除了编码部分,并将我从xml文件中读取的任何数据直接传递给XML解析器,这对我很有效。

票数 0
EN

Stack Overflow用户

发布于 2012-06-27 18:22:57

您需要像这样实现xmlParser委托方法

代码语言:javascript
复制
– parserDidStartDocument:
– parserDidEndDocument:
– parser:didStartElement:namespaceURI:qualifiedName:attributes:
– parser:didEndElement:namespaceURI:qualifiedName:

http://developer.apple.com/library/ios/#documentation/cocoa/reference/NSXMLParserDelegate_Protocol/Reference/Reference.html

当您使用alloc、new、copy、retain时,您将拥有该对象,并且您需要在完成后释放它们。

代码语言:javascript
复制
NSString* str= urlString;
[urlString release];

因为您已经通过将urlstring赋值给str完成了urlstring。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11223919

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档