NSXMLParser didEndElement和didStartElement已被多次调用

时间:2011-11-15 06:34:55

标签: iphone xcode web-services nsxmlparser

我正在使用NSXMLParser来解析从iPad应用程序中的Web服务收到的xml数据。我的问题是didEndElement和didStartElement被多次调用(准确地说是4次)。

以下是方法

-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *) attributeDict 
{

    NSLog(@"did start element");
    if( [elementName isEqualToString:@"WebServiceResult"])
    {

        if (!soapResults)
        {
             //NSLog(@"did start Element");
            soapResults = [[NSMutableString alloc] init];
        }
        elementFound = YES;
    }
}


-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    NSLog(@"did end element");

    if ([elementName isEqualToString:@"WebServiceResult"])
    {
        NSLog(@"Soap Results: %@", soapResults);
        [soapResults setString:@""];
        elementFound = FALSE; 
    }
}

以下是我正在解析的内容

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <authorizePassengerByEmailResponse xmlns="http://tempuri.org/">
      <authorizePassengerByEmailResult>string</authorizePassengerByEmailResult>
    </authorizePassengerByEmailResponse>
  </soap:Body>
</soap:Envelope>

此处字符串inside将是“FirstName LastName”或“Not Authorized”之类的名称。

有关为何发生这种情况的任何建议?

2 个答案:

答案 0 :(得分:2)

这是正确的行为。看,你有4个标签:

  1. <soap:Envelope...
  2. <soap:Body>
  3. <authorizePassengerByEmailResponse xmlns="http://tempuri.org/">
  4. <authorizePassengerByEmailResult>
  5. 因此,每次解析器都会看到它标记为didStartElement的开放标记。

    您将收到以下一堆电话:

    • didStartElement:“soap”
    • didStartElement:“soap”
    • didStartElement:“authorizePassengerByEmailResponse”
    • didStartElement:“authorizePassengerByEmailResult”
    • didEndElement:“authorizePassengerByEmailResult”
    • didEndElement:“authorizePassengerByEmailResponse”
    • didEndElement:“soap”
    • didEndElement:“soap”

答案 1 :(得分:-1)

检查以下URL以进行xml解析:

http://gigaom.com/apple/tutorial-build-a-simple-rss-reader-for-iphone/

如果要从网络解析数据。