0

目的の C 言語を使用して XML ファイルを読み取り、解析しようとしています。XCode 4.2 を使用し、iPhone 用のアプリケーションを作成しています。Viewcontroller .h および .m ファイルを作成しました。私は NSXMLParser を使用しており、xml ファイルの名前は「simple.xml」です。w3schools の Web サイトからダウンロードしました。私は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>

しかし、このコードを実行すると、プログラムが突然終了します。ログに例外情報が表示されません。XCodeでは、この変数を使用している行が「スレッド1が実行を停止しました...」というテキストとともに緑色で表示されるためです。おそらく、XML は ISO-8859-1 でエンコードされており、ASCII エンコードを使用していますか? 以前、Web サービスから返された XML を解析するために同様のコードを使用しましたが、その時点では応答は UTF-8 でエンコードされていました。それとも、メモリ管理で間違いを犯したのでしょうか..allos、リリースなどでしょうか? これで私を助けてください。

また、「TextEdit」で「UTF-8」でファイルを保存しようとしましたが、そのようなオプションはありませんでした。

4

2 に答える 2

0

次のような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,retain を使用すると、オブジェクトを所有し、後でそれらを解放する必要があります。

NSString* str= urlString;
[urlString release];

str に割り当てて urlstring を終了したためです。

于 2012-06-27T10:22:56.963 に答える
0

エンコーディング部分を削除し、xmlファイルから読み取ったデータをXMLパーサーに直接渡しましたが、うまくいきました。

于 2012-06-30T11:42:54.820 に答える