如何在ios中将xml响应解析为uitableview [英] How to parse the xml response into uitableview in ios

查看:141
本文介绍了如何在ios中将xml响应解析为uitableview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析一些xml数据,但是它显示解析失败。下面是代码

I want to parse some xml data ,but its showing parse failed.below is the code

 This my post metod:-
    NSString *soapMessage = [NSString stringWithFormat:
                             @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                              "<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/\">\n"
                              "<soap:Header>\n"
                              "<AuthenticationHeader xmlns=\"Medtech/MMHWebservices/ExternalDeviceData\">\n"
                              "<Username>%@</Username>\n"
                              "<Password>%@</Password>\n"
                              "</AuthenticationHeader>\n"
                              "</soap:Header>\n"
                             "<soap:Body>\n"
                              "<GetAllAlerts xmlns=\"Medtech/MMHWebservices/ExternalDeviceData\" />\n"
                              "</soap:Body>\n"
                              "</soap:Envelope>\n",userName,passWord];
//    NSUserDefaults *default2 = [NSUserDefaults standardUserDefaults];
//    NSString*defaultUrl = [default2 valueForKey:@"url"];
//    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@ManageMyHealthWebService/ExternalApplicationService.asmx",defaultUrl]];
    NSURL * url = [NSURL URLWithString:@"http://192.168.2.119/ManageMyHealthWebService/ExternalApplicationService.asmx"];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];

    [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theRequest addValue: @"Medtech/MMHWebservices/ExternalDeviceData/GetAllAlerts" forHTTPHeaderField:@"SOAPAction"];
    [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection *theConnection =
    [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if( theConnection )
    {
        webData = [NSMutableData data] ;
        NSLog(@"Problem%@",webData);
    }
    else
    {
        NSLog(@"theConnection is NULL");
    }
}

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

    theXML = [theXML stringByReplacingOccurrencesOfString:@"&lt"
                                         withString:@"<"];
    theXML = [theXML stringByReplacingOccurrencesOfString:@"&gt"
                                               withString:@">"];
    theXML = [theXML stringByReplacingOccurrencesOfString:@";"
                                               withString:@""];
    theXML = [theXML stringByReplacingOccurrencesOfString:@";/"
                                               withString:@"/"];

     NSLog(@"response is.....%@",theXML);

//    NSData *myData = [theXML dataUsingEncoding:NSUTF8StringEncoding];
//
//    NSLog(@">>>>>>%@",myData);


    self.xmlParser = [[NSXMLParser alloc] initWithData:webData];
     [self.xmlParser setDelegate:self];
//    [self.xmlParser setShouldProcessNamespaces:NO];
//    [self.xmlParser setShouldReportNamespacePrefixes:NO];
//    [self.xmlParser setShouldResolveExternalEntities:NO];
    [self.xmlParser parse];

    // Run the parser
    [self.xmlParser parse];
    if ([self.xmlParser parse])
    {
        NSLog(@"XML parsing was successful");
        //dispatch_async(dispatch_get_main_queue(), ^{
            //reload the data in the table view
            [self.remindTable reloadData];
       // });

    }
    else{
        NSLog(@"XML parsing failed");
    }
    NSLog(@"Parse Error: %@", [self.xmlParser parserError]);
}

I am getting the response in below format

<pre lang="xml"><?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soap:Body>
    <GetAllAlertsResponse xmlns="Medtech/MMHWebservices/ExternalDeviceData">
      <GetAllAlertsResult>&lt;reminders&gt;  &lt;medication&gt;    &lt;name&gt;Crocin&lt;/name&gt;    &lt;medicationid&gt;822&lt;/medicationid&gt;    &lt;alerttime&gt;15:50,08:00,08:18&lt;/alerttime&gt;    &lt;dow&gt;Sun,Mon,Tue,Wed,Thu,Fri,Sat&lt;/dow&gt;    &lt;unit&gt;&lt;/unit&gt;    &lt;description&gt;&lt;/description&gt;  &lt;/medication&gt;  &lt;medication&gt;    &lt;name&gt;test&lt;/name&gt;    &lt;medicationid&gt;831&lt;/medicationid&gt;    &lt;alerttime&gt;08:00,12:00,18:00&lt;/alerttime&gt;    &lt;dow&gt;Sun,Fri&lt;/dow&gt;    &lt;unit&gt;&lt;/unit&gt;    &lt;description&gt;&lt;/description&gt;  &lt;/medication&gt;&lt;/reminders&gt;</GetAllAlertsResult>
    </GetAllAlertsResponse>
  </soap:Body>
</soap:Envelope>



- (void)解析器:(NSXMLParser * )parser didStartElement:(NSString *)elementName

namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName

attributes:(NSDictionary *)attributeDict

{



NSLog(@在XML文档中找到新元素);



if([elementName isEqualToStri ng:@提醒]){

medicalList = [[NSMutableArray alloc] init];

}



else if([elementName isEqualToString:@drug])

{

self.medic = [[Medications alloc] init];

}



NSLog(@处理元素:%@,elementName);



}



- (void)解析器:(NSXMLParser *)解析器foundCharacters:(NSString *)string {



if(!currentValue)

currentValue = [[NSMutableString alloc] initWithString:string];

else

[currentValue appendString:string];



NSLog(@处理价值:%@,currentValue);



}





//当遇到特定元素的结束标记时,解析器对象发送给它的委托

- (void)解析器:(NSXMLParser *)解析器didEndElement:(NSString *)elementName

namespa ceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName

{



NSString * value = currentValue;

if(currentValue!= nil)

{

value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

}



if([elementName isEqualToString:@提醒])

返回;



else if([elementName isEqualToString:@药物])

{

[medicalList addObject:medic];

medic = nil ;

}



else if([elementName isEqualToString:@name])

{

self.medic.name = value;

NSLog(@当前值....%@,值);

}

else if([elementName isEqualToString:@alerttime])

{

self.medic.alertTime = value;

NSLog(@当前值....%@,值);

}

else if([elementName isEqualToString:@drugid])

{

self.medic.medId = [self.formatter numberFromString:value];

NSLog(@当前值....%@,值);

}





currentValue =零;







任何形式的帮助将不胜感激。谢谢


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

NSLog(@"Found a new element in the XML document");

if([elementName isEqualToString:@"reminders"]){
medicalList = [[NSMutableArray alloc] init];
}

else if([elementName isEqualToString:@"medication"])
{
self.medic = [[Medications alloc] init];
}

NSLog(@"Processing Element: %@", elementName);

}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

if(!currentValue)
currentValue = [[NSMutableString alloc] initWithString:string];
else
[currentValue appendString:string];

NSLog(@"Processing Value: %@", currentValue);

}


//Sent by a parser object to its delegate when it encounters an end tag for a specific element
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{

NSString *value=currentValue;
if (currentValue !=nil)
{
value=[value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

if([elementName isEqualToString:@"reminders"])
return;

else if([elementName isEqualToString:@"medication"])
{
[medicalList addObject:medic];
medic = nil;
}

else if([elementName isEqualToString:@"name"])
{
self.medic.name = value;
NSLog(@"current value....%@",value);
}
else if([elementName isEqualToString:@"alerttime"])
{
self.medic.alertTime = value;
NSLog(@"current value....%@",value);
}
else if([elementName isEqualToString:@"medicationid"])
{
self.medic.medId = [self.formatter numberFromString:value];
NSLog(@"current value....%@",value);
}


currentValue=nil;



Any kind of help will be appreciated. thank you

推荐答案

这篇关于如何在ios中将xml响应解析为uitableview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆