単純な XML 文字列を使用してコードを起動しました
<city>São Paulo</city>
デリゲートで文字を適切に処理していないようです。この XML- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
は、実際には 2 回呼び出されます。1 回目は「S」で、2 回目は「ão Paulo」で呼び出されます。いずれにせよ、このメソッドは一発で完全な文字列を提供するとは限らないため、このような状況に対処する必要があります。
パーサー:見つかった文字:
現在の要素の文字のすべてまたは一部を表す文字列をデリゲートに提供するために、パーサー オブジェクトによって送信されます。
アップデート:
非常に単純な例です。与えられた XML
<cities>
<city>São Paulo</city>
<city>Rio de Janeiro</city>
<city>Salvador</city>
</cities>
このようなパーサーを作成できます
@implementation ParserClass {
NSMutableString *elementText;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
elementText = nil; // we are not handling elements other than "city"
if ([elementName isEqualToString:@"city"]) {
elementText = [NSMutableString new]; // prepare an empty string for city name
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[elementText appendString:string]; // append new characters to the element text
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
// element did end - string now contains text of the element
if ([elementName isEqualToString:@"city"]) {
NSString *cityName = [elementText copy]; // now we have a full city name
...
}
}
...
@end
これは、XML を解析するための一般的なコードではないことに注意してください。もちろん、SAX 構文解析がどのように機能するかを理解している場合は、それを作成することもできます。