1

XML を扱うのはこれが初めてですが、NSXMLParser を使用して学校のカレンダー XML (ここで確認できます) を解析しようとしています。

私の目的では、アイテムのタイトル タグと説明タグの間のテキストを取得するだけで済みます。

私がMac開発者ライブラリで読んだことによると、パーサーが要素にヒットするたびに(parser:didStartElement:namespaceURI:qualifiedName:attribute:メソッドを使用して)、テキストにヒットするたびに(メソッドを使用して)、パーサーがデリゲートに通知を送信するようparser:foundCharacters:です。didStartElement... メソッドを使用して特定の要素に対してのみ処理を行う方法はわかりますが、foundCharacters: メソッドを使用して必要な特定の要素に対してのみテキストを取得する方法がわかりません。これを行う方法はありますか、それとも間違った方法で行っていますか? ありがとう。

4

1 に答える 1

2

foundCharacters呼び出されるのを止めることはできませんが、関心のある 2 つの要素の 1 つであるdidStartElement場合は、何らかのクラス プロパティを設定し、そのクラス プロパティを調べて、それらの文字に対して何かを行うべきかどうかを判断することができます。受信した文字をすぐに返し、効果的に破棄する必要があります。elementNamefoundCharacters

たとえば、これは私のパーサーの簡略化されたバージョンです。

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    // if the element name is in my NSArray of element names I care about ...

    if ([self.elementNames containsObject:elementName])
    {
        // then initialize the variable that I'll use to collect the characters.

        self.elementValue = [[NSMutableString alloc] init];
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    // if the variable to collect the characters is not nil, then append the string

    if (self.elementValue)
    {
        [self.elementValue appendString:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    // if the element name is in my NSArray of element names I care about ...

    if ([self.elementNames containsObject:elementName])
    {
        // step 1, save the data in `elementValue` here (do whatever you want here)

        // step 2, reset my elementValue variable

        self.elementValue = nil;
    }
}

うまくいけば、これでアイデアが得られます。

于 2013-04-17T12:43:55.567 に答える