2010-10-19 92 views
3

XML解析當我從網絡服務接收數據我NSMutableData充滿了以下XML:問題與iPhone

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetWeatherResponse xmlns="http://www.webserviceX.NET"><GetWeatherResult>&lt;?xml version="1.0" encoding="utf-16"?&gt; 
&lt;CurrentWeather&gt; 
    &lt;Location&gt;BERLIN MUNICIPAL AIRPORT, NH, United States (KBML) 44-35N 71-11W 345M&lt;/Location&gt; 
    &lt;Time&gt;Oct 19, 2010 - 03:52 AM EDT/2010.10.19 0752 UTC&lt;/Time&gt; 
    &lt;Wind&gt; Calm:0&lt;/Wind&gt; 
    &lt;Visibility&gt; 10 mile(s):0&lt;/Visibility&gt; 
    &lt;SkyConditions&gt; clear&lt;/SkyConditions&gt; 
    &lt;Temperature&gt; 23.0 F (-5.0 C)&lt;/Temperature&gt; 
    &lt;DewPoint&gt; 21.0 F (-6.1 C)&lt;/DewPoint&gt; 
    &lt;RelativeHumidity&gt; 91&lt;/RelativeHumidity&gt; 
    &lt;Pressure&gt; 29.83 in. Hg (1010 hPa)&lt;/Pressure&gt; 
    &lt;Status&gt;Success&lt;/Status&gt; 
&lt;/CurrentWeather&gt;</GetWeatherResult></GetWeatherResponse></soap:Body></soap:Envelope> 

所以,當我搜索「CurrentWeather」解析器不能找到它,因爲& QT, & lt等。如何解決我的NSMutableData有正常值(<,>等)?

完整代碼

#import "DemoWebServiceConsumeViewController.h" 

@implementation DemoWebServiceConsumeViewController 

@synthesize cityName; 
@synthesize activityIndicator; 
@synthesize location; 

- (IBAction) hideKeyboard{ 
    [cityName resignFirstResponder]; 
} 

- (IBAction) buttonClicked: (id)sender{ 

    [cityName resignFirstResponder];  

    NSString *soapMsg = 
    [NSString stringWithFormat: 
    @"<?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>" 
    "<GetWeather xmlns=\"http://www.webserviceX.NET\">" 
    "<CityName>%@</CityName>" 
    "<CountryName>%@</CountryName>" 
    "</GetWeather>" 
    "</soap:Body>" 
    "</soap:Envelope>", cityName.text, @"united states" 
    ]; 

    NSLog(soapMsg);  

    NSURL *url = [NSURL URLWithString: 
        @"http://www.webservicex.com/globalweather.asmx"]; 
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; 

    //---set the headers--- 
    // here copy method name to be called SOAP Action read from WS description 
    NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]]; 
    [req addValue:@"text/xml; charset=utf-8" 
    forHTTPHeaderField:@"Content-Type"]; 
    [req addValue:@"http://www.webserviceX.NET/GetWeather" 
    forHTTPHeaderField:@"SOAPAction"]; 
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"]; 

    //---set the HTTP method and body--- 
    [req setHTTPMethod:@"POST"]; 
    [req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]]; 


    [activityIndicator startAnimating];  

    conn = [[NSURLConnection alloc] initWithRequest:req delegate:self]; 
    if (conn) { 
     webData = [[NSMutableData data] retain]; 
    } 
} 

-(void) connection:(NSURLConnection *) connection 
didReceiveResponse:(NSURLResponse *) response { 
    [webData setLength: 0]; 
} 

-(void) connection:(NSURLConnection *) connection 
    didReceiveData:(NSData *) data { 
    [webData appendData:data]; 
} 

-(void) connection:(NSURLConnection *) connection 
    didFailWithError:(NSError *) error { 
    [webData release];  
    [connection release]; 
} 

-(void) connectionDidFinishLoading:(NSURLConnection *) connection { 
    NSLog(@"DONE READING WEATHER WEB SERVICE. Received Bytes: %d", [webData length]); 
    NSString *theXML = [[NSString alloc] 
         initWithBytes: [webData mutableBytes] 
         length:[webData length] 
         encoding:NSUTF8StringEncoding]; 
    //---shows the XML--- 
    NSLog(theXML); 

    [theXML release]; 

    [activityIndicator stopAnimating];  

    if (xmlParser) 
    { 
     [xmlParser release]; 
    } 
    xmlParser = [[NSXMLParser alloc] initWithData: webData]; 
       [xmlParser setDelegate:self]; 
       [xmlParser setShouldResolveExternalEntities:YES]; 
       [xmlParser parse]; 


    [connection release]; 
    [webData release]; 
} 

//---when the start of an element is found--- 
-(void) parser:(NSXMLParser *) parser 
    didStartElement:(NSString *) elementName 
    namespaceURI:(NSString *) namespaceURI 
    qualifiedName:(NSString *) qName 
    attributes:(NSDictionary *) attributeDict { 


    NSLog(elementName); 
    if([elementName isEqualToString:@"GetWeatherResult"]) 
    { 
     if (!soapResults) 
     { 
      soapResults = [[NSMutableString alloc] init]; 
     } 
     elementFound = YES; 
    } 
    else if([elementName isEqualToString:@"Location"]) 
    { 
     elementFound = YES; 
    } 
} 

-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string 
{ 
    if (elementFound) 
    { 
     [soapResults appendString: string]; 
    } 
} 

-(void)parser:(NSXMLParser *)parser 
     didEndElement:(NSString *)elementName 
     namespaceURI:(NSString *)namespaceURI 
     qualifiedName:(NSString *)qName 
{ 
    if ([elementName isEqualToString:@"GetWeatherResult"]) 
    { 
     NSLog(soapResults);   
     UIAlertView *alert = [[UIAlertView alloc] 
           initWithTitle:@"Current Temperature!"                     
           message:soapResults 
           delegate:self 
           cancelButtonTitle:@"OK" 
           otherButtonTitles:nil]; 
     [alert show]; 
     [alert release]; 
     [soapResults setString:@""]; 
     elementFound = FALSE; 
    } 
} 

@end 
+1

你可以發佈你做這種轉換的代碼部分嗎?錯誤可能是由於編碼集不正確,但沒有代碼很難說。 – bontoJR 2010-10-19 08:39:36

+0

確實;我們需要先看看您如何檢索數據,然後才能提供幫助。 – 2010-10-19 09:03:45

回答

2

我已經編輯您的問題,所以它顯示了我認爲是你的意思進行粘貼。它看起來像Web服務將整個XML文件封裝爲另一個XML標籤內的字符串。因此,您需要做的是將<GetWeatherResult> XML標記的全部內容作爲單個字符串獲取。我認爲NSXMLParser會自動替換正確的字符來代替&gt;等。

得到該字符串後,您需要將其傳遞到另一個NSXMLParser以解析其內容。

+0

我添加了新的NSXMLParser * weatherXmlParser;在頭文件中。在didEndElement方法中,當我得到有效的XML時,我將它存儲在NSMutableString * soapResults;變量。並嘗試解析它:if​​(weatherXmlParser) \t \t { \t \t \t [weatherXmlParser release]; \t \t} \t \t weatherXmlParser = [[NSXMLParser alloc] initWithData:soapResults]; \t \t [weatherXmlParser setDelegate:self]; \t \t \t [weatherXmlParser setShouldResolveExternalEntities:YES]; \t \t [weatherXmlParser parse];但我得到以下錯誤「拋出'NSException'實例後終止調用 程序接收到的信號:」SIGABRT「。」。 – 1110 2010-10-19 11:02:28

+0

您需要將soapResults轉換爲NSData。 。 – JeremyP 2010-10-19 11:09:41

+0

我很抱歉因爲我無聊:(我說 「的NSData * WDATA = [soapResults dataUsingEncoding:NSUTF8StringEncoding]; \t \t \t \t \t \t的NSLog(WDATA); 」,但我收到新的錯誤:「所謂的終止拋出一個'NSException'的實例後 程序接收到的信號:「SIGABRT」。 「。並且在這個解析方法沒有被調用之後 – 1110 2010-10-19 11:32:53