如何在iphone中解析多个.xml文件? [英] How to parse Multiple .xml files in iphone?

查看:121
本文介绍了如何在iphone中解析多个.xml文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次使用xmls的经历,所以如果我的问题质量低,请不要苛刻。我在应用程序上工作,我使用服务器中的xml文件检索所有数据。



在此处发布问题之前,我读了一些教程。但是当我开始在我的应用程序中实现它时,当我尝试解析第二个Xml文件时,我完全感到困惑,等等。



现在我想要使用一些截图来解释我的应用程序流程,以便每个人都能轻松获得我想要的内容。


  1. 第一视图

  2. 第二个视图

  3. 第三视图

现在当我点击第一个视图中的任意一行时,它会转到第二个视图并在第二个视图中显示所有相关数据,当我点击第二个视图中的任何项目时,它会转到第三个视图并显示有关该特定项目的详细信息。 / p>

在解释应用程序流后,现在我向我展示了我到目前为止所尝试的代码。在教程之后,我只需将类(XMLParser,Book)拖到我的应用程序中进行测试。



代码:

   - (BOOL)应用程序:(UIApplication *)应用程序didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{
NSURL * url = [[NSURL alloc] initWithString:@ Firstviewxmlurl];
NSXMLParser * xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
XMLParser * parser = [[XMLParser alloc] initXMLParser];
[xmlParser setDelegate:parser];
BOOL success = [xmlParser parse];
if(成功)
NSLog(@No Errors);
else
NSLog(@错误错误错误!!!);
}

现在我的XMLParser.m代码是

   - (XMLParser *)initXMLParser {

[super init];

appDelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];

返回自我;
}

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

if([elementName isEqualToString:@Collections]){
//初始化数组。
appDelegate.books = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:@Collection]){

//初始化本书。
aBook = [[book alloc] init];

//在此处提取属性。
aBook.bookID = [[attributeDict objectForKey:@id] integerValue];

NSLog(@读取id值:%i,aBook.bookID);
}

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

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

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

NSLog(@处理值:%@,currentElementValue);
}

- (void)解析器:(NSXMLParser *)解析器didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:@Collections])
return;
if([elementName isEqualToString:@Collection]){
[appDelegate.books addObject:aBook];

[aBook发布];
aBook =零;
}
else
[aBook setValue:currentElementValue forKey:elementName];

[currentElementValue release];
currentElementValue = nil;
}

最终我的第一个视图类代码是

  #pragma mark表方法

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


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// return [tblViewData count] ;
返回[appDelegate.books count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * CellIdentifier = @SimpleTableIdentifier ;
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
//cell.textLabel.text=[[tblViewData objectAtIndex:indexPath.row]
// stringByReplacingOccurrencesOfString:@*withString:@];
Book * aBook = [appDelegate.books objectAtIndex:indexPath.row];

cell.textLabel.text = aBook.title;

if([deviceType isEqualToString:@ipad])
{
[cell.textLabel setFont:[UIFont fontWithName:@Helvetica-Boldsize:20]] ;
}
//cell.textLabel.font=[UIFont fontWithName:@Walkway_SemiBoldsize:16];
返回单元格;
}

执行完所有上述代码后,我得到的结果是这个现在在这一点上我混淆了如何通过我的第二个视图xml文件url然后第三个视图url.my xml文件采用这种格式



第一个xml文件

 <?xml version =1.0encoding =UTF-8?> 
<收藏品> < Collection id =5>< title> Allegroo< / title> < /收集和GT;

第二个xml文件

 <?xml version =1.0encoding =UTF-8?> 
< Collection id =5>< colletciontitle> Allegroo< / colletciontitle> < weaveimage>imageurl< / weaveimage>< Rug id =48>< Rugthumb>firstimageurl< / Rugthumb>< RugSku> AL-637< / RugSku>< / Rug> < Rug id =51>< Rugthumb>Secondimageurl< / Rugthumb>< RugSku> AL-641< / RugSku>< / Rug>

第三个xml文件

 <?xml version =1.0encoding =UTF-8?> 
< Rug id =47>< Rugmainimage>imageurl< / Rugmainimage> < Rugtitle> AL-636 Aged Indigo / Vintage Beige< / Rugtitle> < Rugdiscription>手工打结
仿旧羊毛绒/棉基础< / Rugdiscription><可用><尺寸> 10x14< /尺寸><尺寸> 12x15< /尺寸><尺寸> 2x3< /大小><尺寸> 3x5的< /尺寸><尺寸> 4x6的< /尺寸><尺寸> 6X9< /尺寸><尺寸> 8×10 /尺寸><尺寸> 9x12< /尺寸><转轮> ; 2'6\" ×10' < /转轮><转轮> 2'6\" X12' < /转轮><转轮> 2'6\" ×8' < /转轮>< / Availablesizes>< /地毯>

任何与我的问题和建议有关的链接或示例代码形式的帮助将是高度的appriated.Thanks

解决方案

我添加了一些代码让你理解。尝试根据你的条件实现。下面的代码只是为了引用,因为我没有做出你需要首先理解的所有变化然后相应地实现

  // int i = 0; //在AppDelegate 

代码:

  //或ViewDidLoad方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int = 1; //对于第一个视图
NSURL * url = [[NSURL alloc] initWithString:@Firstviewxmlurl];
NSXMLParser * xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
XMLParser * parser = [[XMLParser alloc] initXMLParser];
[xmlParser setDelegate:parser];
BOOL success = [xmlParser parse];
if(成功)
NSLog(@No Errors);
else
NSLog(@错误错误错误!!!);
}

XMLParser.m

   - (XMLParser *)initXMLParser 
{
[super init];
appDelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];
返回自我;
}

- (void)解析器:(NSXMLParser *)解析器didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
属性:(NSDictionary *)attributeDict {

if([elementName isEqualToString:@Collections])
{
//初始化数组。
if(int == 1)
appDelegate.books = [[NSMutableArray alloc] init];

else if(int == 2)
appDelegate.secondArray = [[NSMutableArray alloc] init];

else if(int == 3)
appDelegate.thirdArray = [[NSMutableArray alloc] init];
}

else if([elementName isEqualToString:@Collection])
{
if(i == 1)
{
//初始化书籍。
aBook = [[book alloc] init];

//在此处提取属性。
aBook.bookID = [[attributeDict objectForKey:@id] integerValue];

NSLog(@读取id值:%i,aBook.bookID);
}

否则如果(i == 2)
{
//第二个Xml
}

否则如果( i == 3)
{
//第三个Xml
}

}

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


- (void)解析器:(NSXMLParser *)解析器foundCharacters:(NSString *)string {
//检查条件
if( !currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];

NSLog(@处理值:%@,currentElementValue);
}

- (void)解析器:(NSXMLParser *)解析器didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
//检查COndition
if([elementName isEqualToString:@Collections])
return;
if([elementName isEqualToString:@Collection]){
[appDelegate.books addObject:aBook];

[aBook发布];
aBook =零;
}
else
[aBook setValue:currentElementValue forKey:elementName];

[currentElementValue release];
currentElementValue = nil;
}


Its my first experience with xmls so please don't be harsh on me if my question is low quality. I am working on app where I retrieve all data using xml files from server.

Before posting question here I read some Tutorials about xml file parsing. But when I start to implement it in my app, then I am totally confused at the point when I am trying to parse the second Xml file and so on.

Now I want to explain my app flow using some screenshot so that it become easy for everyone that what I want.

  1. First view
  2. Second view
  3. Third view

Now when I click in any row in first view it goes to second view and show all related data in second view and when I click any item in Second view it goes to the third view and show detail information about that particular item.

After explanation of app flow, now I show my code what I tried so far. Following a tutorial I just simply drag classes (XMLParser, Book) to my app for testing purpose.

Code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
NSURL *url = [[NSURL alloc] initWithString:@"Firstviewxmlurl"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
XMLParser *parser = [[XMLParser alloc] initXMLParser];
[xmlParser setDelegate:parser];
BOOL success = [xmlParser parse];
if(success)
    NSLog(@"No Errors");
else
    NSLog(@"Error Error Error!!!");
 }

Now my XMLParser.m code is

- (XMLParser *) initXMLParser {

[super init];

appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

return self;
  }

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

if([elementName isEqualToString:@"Collections"]) {
    //Initialize the array.
    appDelegate.books = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:@"Collection"]) {

    //Initialize the book.
    aBook = [[Book alloc] init];

    //Extract the attribute here.
    aBook.bookID = [[attributeDict objectForKey:@"id"] integerValue];

    NSLog(@"Reading id value :%i", aBook.bookID);
}

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

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

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

NSLog(@"Processing Value: %@", currentElementValue);
}

 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
   namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:@"Collections"])
    return;
if([elementName isEqualToString:@"Collection"]) {
    [appDelegate.books addObject:aBook];

    [aBook release];
    aBook = nil;
}
else 
    [aBook setValue:currentElementValue forKey:elementName];

[currentElementValue release];
currentElementValue = nil;
  }

Finaly my First view Class code is

    #pragma mark Table Methods

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


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
 {
//return [tblViewData count];
return [appDelegate.books count];
 }

  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    {
static NSString *CellIdentifier = @"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{
    cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    cell.selectionStyle=UITableViewCellSelectionStyleGray;
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
}
//cell.textLabel.text=[[tblViewData objectAtIndex:indexPath.row]
                    // stringByReplacingOccurrencesOfString:@"*" withString:@""];
   Book *aBook = [appDelegate.books objectAtIndex:indexPath.row];

cell.textLabel.text = aBook.title;

if([deviceType isEqualToString:@"ipad"])
{
    [cell.textLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
}
//cell.textLabel.font=[UIFont fontWithName:@"Walkway_SemiBold" size:16];
return cell;
   }

After implementation of all the above Code i got the result in form of this Now at this point i confuse how can i pass my Second view xml file url and then third view url.my xml files are in this format

First xml file

 <?xml version="1.0" encoding="UTF-8"?>
<Collections> <Collection id="5"><title>Allegroo</title> </Collection>

Second xml file

 <?xml version="1.0" encoding="UTF-8"?>
 <Collection id="5"><colletciontitle>Allegroo</colletciontitle>  <weaveimage>"imageurl"   </weaveimage><Rug id="48"><Rugthumb>"firstimageurl"</Rugthumb><RugSku>AL-637</RugSku></Rug><Rug id="51"><Rugthumb>"Secondimageurl"</Rugthumb><RugSku>AL-641</RugSku></Rug>

Third xml file

  <?xml version="1.0" encoding="UTF-8"?>
 <Rug id="47"><Rugmainimage>"imageurl"</Rugmainimage> <Rugtitle>AL-636 Aged Indigo / Vintage Beige</Rugtitle> <Rugdiscription>Hand Knotted
  Distressed Wool Pile / Cotton Foundation </Rugdiscription><Availablesizes><Size>10x14</Size><Size>12x15</Size><Size>2x3</Size><Size>3x5</Size><Size>4x6</Size><Size>6x9</Size><Size>8x10</Size><Size>9x12</Size><Runner>2'6"x10'</Runner><Runner>2'6"x12'</Runner><Runner>2'6"x8'</Runner></Availablesizes></Rug>

Any help in the form of link or sample code releated to my issue and suggestion will be highly appriated.Thanks

解决方案

I have added some of the code to make you understand. Try to implement according to your condition. Below code is just to refer as i havn't made all the changes u need to understand first and then implement accordingly

//int i = 0;   // in AppDelegate

Code:

//Or ViewDidLoad Method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 int = 1;    //For First View
NSURL *url = [[NSURL alloc] initWithString:@"Firstviewxmlurl"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
XMLParser *parser = [[XMLParser alloc] initXMLParser];
[xmlParser setDelegate:parser];
BOOL success = [xmlParser parse];
if(success)
    NSLog(@"No Errors");
else
    NSLog(@"Error Error Error!!!");
 }

XMLParser.m

- (XMLParser *) initXMLParser 
    {  
      [super init];
      appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
      return self;
    }

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

    if([elementName isEqualToString:@"Collections"]) 
   {
        //Initialize the array.
      if (int == 1)
        appDelegate.books = [[NSMutableArray alloc] init];

      else if (int == 2)
        appDelegate.secondArray = [[NSMutableArray alloc] init];

      else if (int == 3)
        appDelegate.thirdArray = [[NSMutableArray alloc] init];
    }

    else if([elementName isEqualToString:@"Collection"]) 
  {
         if (i == 1)
        {
          //Initialize the book.
          aBook = [[Book alloc] init];

          //Extract the attribute here.
          aBook.bookID = [[attributeDict objectForKey:@"id"] integerValue];

          NSLog(@"Reading id value :%i", aBook.bookID);
        }

         else if (i == 2)
        {
           //Second Xml 
        }

        else if (i == 3)
       {
           //Third Xml
       }

    }

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


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
    //Check condition 
    if(!currentElementValue) 
        currentElementValue = [[NSMutableString alloc] initWithString:string];
    else
        [currentElementValue appendString:string];

    NSLog(@"Processing Value: %@", currentElementValue);
    }

     - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
       namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
//Check COndition
    if([elementName isEqualToString:@"Collections"])
        return;
    if([elementName isEqualToString:@"Collection"]) {
        [appDelegate.books addObject:aBook];

        [aBook release];
        aBook = nil;
    }
    else 
        [aBook setValue:currentElementValue forKey:elementName];

    [currentElementValue release];
    currentElementValue = nil;
      }

这篇关于如何在iphone中解析多个.xml文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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