• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 如何在 Xcode 中解析 XML 页面中的图像?

[复制链接]
菜鸟教程小白 发表于 2022-12-12 09:56:31 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

您好,我正在开发一个新闻 iOS 应用程序,我正在从 XML 获取标题和描述,但我无法从 XML 获取图像,谁能帮我解决这个问题。

注意:我是这个 iOS 开发的新手,请帮我解决这个问题。提前致谢。

这是我的代码。

在 NewsViewController.h 中

#import <UIKit/UIKit.h>

@interface NewsViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,NSXMLParserDelegate>
@property (strong,nonatomic)IBOutlet UITableView *tblNews;
@property (strong,nonatomic)IBOutlet NSMutableArray *arrTitles;
@property (strong,nonatomic)IBOutlet NSMutableArray *arrDescription;
@property (strong,nonatomic)IBOutlet NSMutableArray *arrImages;
@property (strong,nonatomic)IBOutlet NSMutableArray *arrDate;

@end

在 NewsViewController.m 中

#import "NewsViewController.h"
#import "NewsTableViewCell.h"
#import "NewDetailsViewController.h"

@interface NewsViewController ()
{
    NSString *temString;
    NSMutableString *strTemp;
}

@end

@implementation NewsViewController
@synthesize arrImages;

- (id)initWithNibNameNSString *)nibNameOrNil bundleNSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

#pragma mark - View Life Cycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.arrTitles =[[NSMutableArray alloc] init];
    self.arrDescription=[[NSMutableArray alloc]init];
    self.arrImages=[[NSMutableArray alloc]init];
    self.arrDate=[[NSMutableArray alloc]init];
    [self makeRequestForNews];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma  mark - make request for news
-(void)makeRequestForNews//http://www.shura.bh/MediaCenter/News/ExportNewsAsXml.aspx?Section=%D8%A3%D8%AE%D8%A8%D8%A7%D8%B1%20%D8%A7%D9%84%D9%85%D8%AC%D9%84%D8%B3
{
    NSURL *url =[NSURL URLWithString"http://www.shura.bh/MediaCenter/News/ExportNewsAsXml.aspx?Section=%D8%A3%D8%AE%D8%A8%D8%A7%D8%B1%20%D8%A7%D9%84%D9%85%D8%AC%D9%84%D8%B3&RetrieveImageUrl=true"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //After making request the apparent thing is expecting the response that may be expected response or an Error. so create those objects and intialize them with NULL.
    NSURLResponse *response = NULL;
    NSError *requestError =NULL;
    //Once you have response with you , Capture YOur Responce data using NsData.

    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];

    //Convert the respnse Data into Response String.

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    //Now We can start parsing the Data using XMl parser . you need XML parser in-order to use the below class method "dictionaryFOrXMLString".

    NSError *parserError = NULL;

    //XML parsing

    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:responseData];
    [xmlParser setDelegate:self];
    [xmlParser parse];

  //NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:NULL];

    //once you have xmlDict handy, you can pass this to the any ViewController (Like table view) to populate the Data.

}

- (void)parserDidEndDocumentNSXMLParser *)parser {

    NSURL *imageURL = [NSURL URLWithString:[arrImages objectAtIndex:0]];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *image = [UIImage imageWithData:imageData];
}
-(void)parserNSXMLParser *)parser didStartElementNSString *)elementName namespaceURINSString *)namespaceURI qualifiedNameNSString *)qName attributesNSDictionary *)attributeDict
{
    if ([elementName isEqualToString"ShuraNews"])
    {

    }
    if ([elementName isEqualToString"UBLISHINGPAGEIMAGE"])
    {

        NSLog(@"dict === %@",attributeDict);
    }
    strTemp=[NSMutableString new];
}
-(void)parserNSXMLParser *)parser foundCharactersNSString *)string
{
    //temString =string;
    [strTemp appendString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString"TITLE"])
    {
        NSLog(@"temstring=== %@", strTemp);
        [self.arrTitles addObject:strTemp];
    }
    if ([elementName isEqualToString"UBLISHINGPAGECONTENT"])
    {
        NSLog(@"temstring=== %@", strTemp);
        [self.arrDescription addObject:strTemp];
    }
    if ([elementName isEqualToString"NEWSARTICLEDATE"])
    {
        NSLog(@"temstring=== %@", strTemp);
        [self.arrDate addObject:strTemp];
    }
    if ([elementName isEqualToString"UBLISHINGPAGEIMAGE"])
    {
        NSURL *PUBLISHINGPAGEIMAGE = [NSURL URLWithString"strImage"];
        NSData *data = [NSData dataWithContentsOfURLUBLISHINGPAGEIMAGE];
        UIImage *arrImages = [[UIImage alloc] initWithData:data];
        NSLog(@"temstring=== %@", strTemp);
        [self.arrImages addObject:strTemp];
    }
    if ([elementName isEqualToString"ShuraNews"])
    {

        [self.tblNews reloadData];
    }
}
#pragma mark - TabeView Datasource//delegate method

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.arrTitles count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView setSeparatorInset:UIEdgeInsetsZero];
    static NSString *cellIdentifier=@"cellNews";
    NewsTableViewCell *cell=(NewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    if (cell == nil)
    {
        cell = [[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        // cell.NewsTableViewCell.textColor = UIColorFromRGB(0x000000);
        cell.backgroundColor=[UIColor clearColor];
    }
    if( [indexPath row] % 2){
        cell.contentView.backgroundColor =UIColorFromRGB(0Xffffff);

    }
    else{
        cell.contentView.backgroundColor =UIColorFromRGB (0Xdcdcdc);
    }

    //selectbackgroun color start
    UIView *NewsTableViewCell = [[UIView alloc] initWithFrame:cell.frame];
    NewsTableViewCell.backgroundColor = UIColorFromRGB(0Xdcdcdc);
    cell.selectedBackgroundView = NewsTableViewCell; //select background colro end
    cell.lblTitles.font = [UIFont fontWithName"GEEast-ExtraBold" size:12];
    cell.lblTitles.text=[self.arrTitles objectAtIndex:indexPath.row];
    cell.lblDescription.font =[UIFont fontWithName:@"GE SS Unique" size:12];
    cell.lblDate.font=[UIFont fontWithName:@"GE SS Unique" size:12];
    cell.lblDescription.text=[self.arrDescription objectAtIndex:indexPath.row];
    cell.lblDate.text=[self.arrDate objectAtIndex:indexPath.row];
    cell.lblTitles.textAlignment= NSTextAlignmentRight;
    cell.lblDate.textAlignment = NSTextAlignmentRight;
    cell.lblDescription.textAlignment = NSTextAlignmentRight;
   // cell.imgNews.image = [UIImage imageNamed:@"homeh"];
  //  cell.imgNews.image=[self.arrImages objectAtIndex:indexPath.row];
    UIImage *arrImages = [[UIImage alloc]initWithData:arrImages];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:@"%@",
        [self.arrTitles objectAtIndex:indexPath.row]],@"title",[NSString stringWithFormat:@"%@",
        [self.arrImages objectAtIndex:indexPath.row]],@"img",[NSString stringWithFormat:@"%@",
        [self.arrDescription objectAtIndex:indexPath.row]],@"Des", nil];

    [self performSegueWithIdentifier:@"NewsDetailsID" sender:dict];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"NewsDetailsID"])
    {
        ((NewDetailsViewController *)segue.destinationViewController).strTitle=[sender objectForKey:@"title"];
        ((NewDetailsViewController *)segue.destinationViewController).strDescription=[sender objectForKey:@"Des"];
    }
}

@end

我的 XML 格式是:

<ShuraNews>
    <QueryProperties>...</QueryProperties>
    <Articles TotalItems="256" TotalRowsExactToReturnItems="False">
    <Article ItemNo="1">
    <URL>
    http://www.shura.bh/MediaCenter/News/CouncilNews/Pages/14-05-14(2).aspx
    </URL>
    <TITLE>
    فيما أشاد رئيس "الشؤون الخارجية" في البرلمان الايرلندي بالتطور الاقتصادي بالمملكة .. الجشي: علاقاتنا مع ايرلندا ايجابية..ونأمل بالمزيد من التعاون البرلماني والتجاري بين البلدين
    </TITLE>
    <AUTHOR></AUTHOR>
    <RANK>1000</RANK>
    <DESCRIPTION/>
    <WRITE>15/05/2014 01:05:55 ص</WRITE>
    <ISDOCUMENT>1</ISDOCUMENT>
    <SIZE>83798</SIZE>
    <SITENAME>http://www.shura.bh/mediacenter/news/councilnews</SITENAME>
    <CREATED/>
    <NEWSARTICLEDATE>13/05/2014 05:00:00 م</NEWSARTICLEDATE>
    <CONVENIENTPERIOD>الرابع</CONVENIENTPERIOD>
    <TERM>الثالث</TERM>
    <UBLISHINGPAGEIMAGE>
    <img alt="" border=1 src="/MediaCenter/News/Committees/HRC/PublishingImages/DSC_5804.JPG" width=450 style="border:1px solid">
    </PUBLISHINGPAGEIMAGE>
    <UBLISHINGPAGECONTENT>
    القضيبية – مجلس الشورى اكدت سعادة الدكتورة بهية جواد الجشي النائب الثاني لرئيس مجلس الشورى رئيسة لجنة الصداقة البحرينية الايرلندية بالمجلس على أن مملكة البحرين تولي اهتماما كبيرا لإقامة علاقات تعاون مع مختلف دول العالم في إطار من الاحترام المتبادل والمصالح المشتركة، مشيرة إلى أن العلاقات مع جمهورية إيرلندا تحظى بالتقدير والاعتزاز، معربة في الوقت ذاته عن أملها في أن تنعكس تلك العلاقات الإيجابية على رفع مستوى التعاون البرلماني والتجاري بين البلدين، منوهة بالدور المحوري للجان الصداقة البرلمانية على صعيد تقريب وجهات النظر وتبادل الآراء حول مختلف الموضوعات محل الاهتمام المشترك. واعربت الجشي عن ترحيبها بالزيارة التي يقوم بها سعادة السيد بات برين رئيس لجنة الشؤون الخارجية والتجارة في البرلمان الإيرلندي الى مملكة البحرين،  والتي من شأنها البناء على علاقات الصداقة المتميزة والوثيقة القائمة بين البلدين، والارتقاء بها نحو مجالات أرحب من التعاون بما يخدم  البلدين والشعبين الصديقين، حيث تضمنت الزيارة لقاء معالي رئيس مجلس النواب، ووزير التجارة والصناعة وبالمملكة، إلى جانب زيارة شركة الخليج لصناعة البتروكيماويات ومنطقة البحرين العالمية للاستثمار. من جانبه، أشار رئيس لجنة الشؤون الخارجية والتجارة في البرلمان الايرلندي إلى ان العلاقات القائمة بين مملكة البحرين وجمهورية ايرلندا هي علاقات ايجابية ومتنامية في مختلف المجالات، مشيدا بالتطورات الاقتصادية الجارية في مملكة البحرين، فيما اكد على اهمية الزيارة الاخيرة التي قام بها وفد لجنة الصداقة البحرينية الايرلندية بمجلس الشورى إلى جمهورية ايرلندا، وما اسهمت به الدعوة التي تلقاها من رئيسة الوفد سعادة الدكتورة بهية الجشي لزيارة المملكة في فتح القنوات لتطوير العلاقات القائمة بين مملكة البحرين وجمهورية ايرلندا.
    </PUBLISHINGPAGECONTENT>
    <COMMENTS>
    اكدت سعادة الدكتورة بهية جواد الجشي النائب الثاني لرئيس مجلس الشورى رئيسة لجنة الصداقة البحرينية الايرلندية بالمجلس على أن مملكة البحرين تولي اهتماما كبيرا لإقامة علاقات تعاون مع مختلف دول العالم في إطار من الاحترام المتبادل والمصالح المشتركة
    </COMMENTS>
    <ARTICLEBYLINE/>
    <UBLISHINGROLLUPIMAGE>
    <img alt="" border=1 src="/MediaCenter/News/Committees/HRC/PublishingImages/DSC_5804.JPG" style="border:1px solid">
    </PUBLISHINGROLLUPIMAGE>
    </Article>
    </ShuraNews>



Best Answer-推荐答案


好的,有很多问题:

  1. 从技术上讲,XML 格式不正确。您的 XML 包含:

    <UBLISHINGPAGEIMAGE>
    <img alt="" border=1 src="/MediaCenter/News/Committees/HRC/PublishingImages/DSC_5804.JPG" width=450 style="border:1px solid">
    </PUBLISHINGPAGEIMAGE>
    

    如果这确实是您的 XML 的样子,那么它的格式不正确。此 URL 应包含在 CDATA 中(即以 开头并以 ]]> 结尾)或 <>& 应替换为 <>&,分别。这意味着它应该看起来像:

    <UBLISHINGPAGEIMAGE>
    &lt;img alt="" border=1 src="/MediaCenter/News/Committees/HRC/PublishingImages/DSC_5804.JPG" width=450 style="border:1px solid"&gt;
    </PUBLISHINGPAGEIMAGE>
    

    <UBLISHINGPAGEIMAGE>
    <![CDATA[<img alt="" border=1 src="/MediaCenter/News/Committees/HRC/PublishingImages/DSC_5804.JPG" width=450 style="border:1px solid">]]>
    </PUBLISHINGPAGEIMAGE>
    

    因此,如果您解决此问题,您就可以成功检索 PUBLISHINGPAGEIMAGE 的值。

  2. 完成后,您现在需要从该 HTML 中提取 URL。要正确执行此操作,您可能应该使用 HTML 解析器,例如 HPPLE,但对于像这样简单的事情,您也可以使用正则表达式:

    - (NSString *)findFirstImgUrlInString:(NSString *)string
    {
        NSError *error = NULL;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(<img\\s[\\s\\S]*?src\\s*?=\\s*?['\"](.*?)['\"][\\s\\S]*?>)+?"
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:&error];
    
        NSTextCheckingResult *result = [regex firstMatchInString:string
                                                         options:0
                                                           range:NSMakeRange(0, [string length])];
    
        if (result)
            return [string substringWithRange:[result rangeAtIndex:2]];
    
        return nil;
    }
    
  3. 完成后,您可以为 img HTML 标记提取 src。请注意,这是一个相对 URL:

    /MediaCenter/News/Committees/HRC/PublishingImages/DSC_5804.JPG
    

    您显然必须确定基本 URL 是,然后将此 URL 附加到它。看来您必须从 XML 中获取名为 URL 的元素,从中提取基本 URL,然后将上述图像 URL 附加到该元素。

关于ios - 如何在 Xcode 中解析 XML 页面中的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23722052/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap