如何在iPhone上解析XML

时间:2012-02-27 11:00:49

标签: iphone xml-parsing

  

可能重复:
  iPhone Development - XMLParser vs. libxml2 vs. TouchXML

如何解析以下响应以获取Id,RegionId和CountryName等数据元素?请帮我解决iPhone中的问题。

<feed xml:base="http://infra2appsmobile.cloudapp.net/Infra2Apps.svc/" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
  <title type="text">Countries</title>
  <id>http://infra2appsmobile.cloudapp.net/Infra2Apps.svc/Countries</id>
  <updated>2012-02-27T10:55:19Z</updated>
  <link rel="self" title="Countries" href="Countries" />
  <entry>
    <id>http://infra2appsmobile.cloudapp.net/Infra2Apps.svc/Countries(14)</id>
    <title type="text"></title>
    <updated>2012-02-27T10:55:19Z</updated>
    <author>
      <name />
    </author>
    <link rel="edit" title="Country" href="Countries(14)" />
    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Region" type="application/atom+xml;type=entry" title="Region" href="Countries(14)/Region" />
    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Contact_Country" type="application/atom+xml;type=feed" title="Contact_Country" href="Countries(14)/Contact_Country" />
    <category term="HpSalesPortalMobileDBModel.Country" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
    <content type="application/xml">
      <m:properties>
        <d:Id m:type="Edm.Int16">14</d:Id>
        <d:RegionId m:type="Edm.Byte">1</d:RegionId>
        <d:CountryName>France</d:CountryName>
      </m:properties>
    </content>
  </entry>
  <entry>
    <id>http://infra2appsmobile.cloudapp.net/Infra2Apps.svc/Countries(15)</id>
    <title type="text"></title>
    <updated>2012-02-27T10:55:19Z</updated>
    <author>
      <name />
    </author>
    <link rel="edit" title="Country" href="Countries(15)" />
    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Region" type="application/atom+xml;type=entry" title="Region" href="Countries(15)/Region" />
    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Contact_Country" type="application/atom+xml;type=feed" title="Contact_Country" href="Countries(15)/Contact_Country" />
    <category term="HpSalesPortalMobileDBModel.Country" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
    <content type="application/xml">
      <m:properties>
        <d:Id m:type="Edm.Int16">15</d:Id>
        <d:RegionId m:type="Edm.Byte">1</d:RegionId>
2012-02-27 16:25:18.933 SampleTest[571:f803] >>>>>>>>>>  Route data <?xml version="1.0" encoding="utf-8" standalone="yes"?>
<feed xml:base="http://infra2appsmobile.cloudapp.net/Infra2Apps.svc/" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
  <title type="text">Countries</title>
  <id>http://infra2appsmobile.cloudapp.net/Infra2Apps.svc/Countries</id>
  <updated>2012-02-27T10:55:19Z</updated>
  <link rel="self" title="Countries" href="Countries" />
  <entry>
    <id>http://infra2appsmobile.cloudapp.net/Infra2Apps.svc/Countries(14)</id>
    <title type="text"></title>
    <updated>2012-02-27T10:55:19Z</updated>
    <author>
      <name />
    </author>
    <link rel="edit" title="Country" href="Countries(14)" />
    <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Region" type="application/atom+xml;type=entry" title="Region" href="Countries(14)/Region" />
    <link rel="h

嗨马丁我使用你的代码如下,但我无法解析数据我的意思是无法解析像id,RegionId和Countryname这样的特定数据,也没有进入for(){}。 给我解决方法如何解析数据。

NSArray * array = [thexml componentsSeparatedByString:@“”];         NSLog(@“%d”,[数组计数]);         的NSLog(@“-------------&GT;&GT;&GT;&GT;&GT;&GT;&GT;&GT;&GT;&GT;&GT; 23344&LT;&LT;&LT;&LT;&LT;&LT ;&lt;&lt;&lt;&lt; ---------%d“,[数组计数]); // NSString * str1 = [array objectAtIndex:0]; //
// NSArray * array1 = [str1 componentsSeparatedByString:@“”]; // NSLog(@“%d”,[array1 count]);         for(int i = 1; i&lt; [array count]; i ++)         {             NSLog(@“-------------&gt;&gt;&gt;&gt;&gt;&gt;&gt; ---------%d”,[数组计数]);

        NSString *str=[array objectAtIndex:i];
        NSLog(@"------------->>>>>>>>><<<<<<<<<---------%@",str);
        NSArray *arr1=[str componentsSeparatedByString:@"<text>"];
        NSLog(@"------------->>>>>>>>>>>1111<<<<<<<<<---------%@",arr1);

        NSString *data=[arr1 objectAtIndex:1];
        NSRange ranfrom=[data rangeOfString:@"</text>"];
        // nt.truckName=[data substringToIndex:ranfrom.location];
        [tweets  addObject:[data substringToIndex:ranfrom.location]];
        NSLog(@"------------->>>>>>>>>>>2222<<<<<<<<<---------%@",tweets);
    }

2012-02-28 13:38:38.609 SampleTest [358:f803] -------------&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&lt; &LT;&LT;&LT;&LT;&LT;&LT;&LT;&LT; --------- 1

2 个答案:

答案 0 :(得分:1)

NSXMLParser是最佳解决方案。

使用NSXMLParserDelegate

声明委托类
@interface myXMLReader : NSObject <NSXMLParserDelegate> 

在委托类中实现解析方法

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    ...
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    ...
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    ...
}

然后开始解析。

NSData * kmlData = [NSData dataWithContentsOfFile:urlOfXml];
if(kmlData != nil){
    NSXMLParser * parser  = [[NSXMLParser alloc] initWithData:kmlData];
    [parser setDelegate:self];
    [parser parse]; 
    [parser release];
}

享受

答案 1 :(得分:1)

我解析xml的方式与其他方式不同,坦白说我真的不知道它是哪种技术但是我向你保证它对我来说很好,我已经在很多项目中成功实现了它。看一下我从一些profile

加载推文的代码
  

这是我调用解析器的函数。

-(void)loadtweet
{
@try
{
    NSString *urlString = [NSString stringWithFormat:@"https://api.twitter.com/1/statuses/user_timeline.xml?screen_name=SrBachchan&count=5"];

    NSLog(@"fetching data from--------> : %@",urlString);

    NSString* escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

    NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:escapedUrlString]];

    NSURLConnection *con=[[NSURLConnection alloc]  initWithRequest:request1 delegate:self];
    if(con)
        truckData=[[NSMutableData data]retain];
}

@catch (NSException *exception) 
{
    UIAlertView *v = [[UIAlertView alloc] initWithTitle:@"ERROR" message:@"Please Try Again Later." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [v show];
    [v release];
}

}
  

这些是NSURLConnection委托方法:

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

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

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 

{
   [tweets removeAllObjects];
 @try 
{
    // [app.trucks removeAllObjects];
    NSString *thexml=[[NSString alloc] initWithBytes:[truckData mutableBytes] length:[truckData length] encoding:NSUTF8StringEncoding];

    NSArray *array=[thexml componentsSeparatedByString:@"<status>"];
    NSLog(@"%d",[array count]);

    for(int i=1;i<[array count];i++)
    {
        NSString *str=[array objectAtIndex:i];
        NSArray *arr1=[str componentsSeparatedByString:@"<text>"];
        NSString *data=[arr1 objectAtIndex:1];
        NSRange ranfrom=[data rangeOfString:@"</text>"];
        // nt.truckName=[data substringToIndex:ranfrom.location];
        [tweets  addObject:[data substringToIndex:ranfrom.location]];
    }
}

@catch (NSException *exception) 
{
    UIAlertView *v = [[UIAlertView alloc] initWithTitle:@"ERROR" message:@"Please Try Again Later." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [v show];
    [v release];
 }

}

我使用了一些字符串函数来分隔标记并将值存储在Array中。