使用目标C(iOS 5)读取XML文件



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

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内容 -

<?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>

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

我也尝试在"文本编辑"中使用"UTF-8"保存文件,但没有这样的选项可用。

你需要实现 xmlParser Delegate 方法,如

– 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,保留时,您拥有该对象,并且您需要稍后释放它们。

NSString* str= urlString;
[urlString release];

因为您已经通过分配给 str 完成了 url 字符串。

删除了

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

最新更新