English 中文(简体)
阅读手机XML文档
原标题:Reading XML file in Iphone

I am new in Iphone, and i know there are lot of tutorials available, also I have searched alot, but still failed in reading the following XML file. Hope you will help me. I want to read followings. 1. ViewCounts 2. Media:Thumbnail 3. Media:Title 4. NumRates 5. Duration

提前感谢。

<?xml version="1.0" ?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005" xmlns:media="http://search.yahoo.com/mrss/" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:yt="http://gdata.youtube.com/schemas/2007">
  <id>
    http://gdata.youtube.com/feeds/api/videos
  </id>
  <updated>
    2012-04-08T15:09:04.640Z
  </updated>
  <category scheme="http://schemas.google.com/g/2005#kind" term="http://gdata.youtube.com/schemas/2007#video"/>
  <title type="text">
    YouTube Videos matching query: pakistan
  </title>
  <logo>
    http://www.youtube.com/img/pic_youtubelogo_123x63.gif
  </logo>
  <link href="http://www.youtube.com" rel="alternate" type="text/html"/>
  <link href="http://gdata.youtube.com/feeds/api/videos" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/>
  <link href="http://gdata.youtube.com/feeds/api/videos/batch" rel="http://schemas.google.com/g/2005#batch" type="application/atom+xml"/>
  <link href="http://gdata.youtube.com/feeds/api/videos?alt=atom&start-index=1&max-results=1&vq=pakistan&orderby=relevance" rel="self" type="application/atom+xml"/>
  <link href="http://gdata.youtube.com/feeds/api/videos?alt=atom&start-index=2&max-results=1&vq=pakistan&orderby=relevance" rel="next" type="application/atom+xml"/>
  <author>
    <name>
      YouTube
    </name>
    <uri>
      http://www.youtube.com/
    </uri>
  </author>
  <generator uri="http://gdata.youtube.com" version="2.1">
    YouTube data API
  </generator>
  <openSearch:totalResults>
    1000000
  </openSearch:totalResults>
  <openSearch:startIndex>
    1
  </openSearch:startIndex>
  <openSearch:itemsPerPage>
    1
  </openSearch:itemsPerPage>
  <entry>
    <id>
      http://gdata.youtube.com/feeds/api/videos/QP9K2YeO6kE
    </id>
    <published>
      2012-04-08T05:51:35.000Z
    </published>
    <updated>
      2012-04-08T14:18:21.000Z
    </updated>
    <category scheme="http://schemas.google.com/g/2005#kind" term="http://gdata.youtube.com/schemas/2007#video"/>
    <category label="News & Politics" scheme="http://gdata.youtube.com/schemas/2007/categories.cat" term="News"/>
    <category scheme="http://gdata.youtube.com/schemas/2007/keywords.cat" term="Pakistan"/>
    <category scheme="http://gdata.youtube.com/schemas/2007/keywords.cat" term="Avalanche"/>
    <title type="text">
      Avalanche Buries More Than 100 Pakistani Troops
    </title>
    <content type="text">
      Pakistani soldiers dug into a massive avalanche in a mountain battleground close to the Indian border on Saturday, searching for at least 135 people buried when the wall of snow engulfed a military complex. (April 7)
    </content>
    <link href="http://www.youtube.com/watch?v=QP9K2YeO6kE&feature=youtube_gdata" rel="alternate" type="text/html"/>
    <link href="http://gdata.youtube.com/feeds/api/videos/QP9K2YeO6kE/responses" rel="http://gdata.youtube.com/schemas/2007#video.responses" type="application/atom+xml"/>
    <link href="http://gdata.youtube.com/feeds/api/videos/QP9K2YeO6kE/related" rel="http://gdata.youtube.com/schemas/2007#video.related" type="application/atom+xml"/>
    <link href="http://m.youtube.com/details?v=QP9K2YeO6kE" rel="http://gdata.youtube.com/schemas/2007#mobile" type="text/html"/>
    <link href="http://gdata.youtube.com/feeds/api/videos/QP9K2YeO6kE" rel="self" type="application/atom+xml"/>
    <author>
      <name>
        AssociatedPress
      </name>
      <uri>
        http://gdata.youtube.com/feeds/api/users/AssociatedPress
      </uri>
    </author>
    <gd:comments>
      <gd:feedLink countHint="55" href="http://gdata.youtube.com/feeds/api/videos/QP9K2YeO6kE/comments" rel="http://gdata.youtube.com/schemas/2007#comments"/>
    </gd:comments>
    <yt:location>
      New York, NY
    </yt:location>
    <media:group>
      <media:category label="News & Politics" scheme="http://gdata.youtube.com/schemas/2007/categories.cat">
        News
      </media:category>
      <media:content duration="53" expression="full" isDefault="true" medium="video" type="application/x-shockwave-flash" url="http://www.youtube.com/v/QP9K2YeO6kE?version=3&f=videos&app=youtube_gdata" yt:format="5"/>
      <media:content duration="53" expression="full" medium="video" type="video/3gpp" url="rtsp://v6.cache4.c.youtube.com/CiILENy73wIaGQlB6o6H2Ur_QBMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp" yt:format="1"/>
      <media:content duration="53" expression="full" medium="video" type="video/3gpp" url="rtsp://v4.cache8.c.youtube.com/CiILENy73wIaGQlB6o6H2Ur_QBMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp" yt:format="6"/>
      <media:description type="plain">
        Pakistani soldiers dug into a massive avalanche in a mountain battleground close to the Indian border on Saturday, searching for at least 135 people buried when the wall of snow engulfed a military complex. (April 7)
      </media:description>
      <media:keywords>
        Pakistan, Avalanche
      </media:keywords>
      <media:player url="http://www.youtube.com/watch?v=QP9K2YeO6kE&feature=youtube_gdata_player"/>
      <media:thumbnail height="360" time="00:00:26.500" url="http://i.ytimg.com/vi/QP9K2YeO6kE/0.jpg" width="480"/>
      <media:thumbnail height="90" time="00:00:13.250" url="http://i.ytimg.com/vi/QP9K2YeO6kE/1.jpg" width="120"/>
      <media:thumbnail height="90" time="00:00:26.500" url="http://i.ytimg.com/vi/QP9K2YeO6kE/2.jpg" width="120"/>
      <media:thumbnail height="90" time="00:00:39.750" url="http://i.ytimg.com/vi/QP9K2YeO6kE/3.jpg" width="120"/>
      <media:title type="plain">
        Avalanche Buries More Than 100 Pakistani Troops
      </media:title>
      <yt:duration seconds="53"/>
    </media:group>
    <gd:rating average="4.7647057" max="5" min="1" numRaters="17" rel="http://schemas.google.com/g/2005#overall"/>
    <yt:recorded>
      2012-04-08
    </yt:recorded>
    <yt:statistics favoriteCount="4" viewCount="662"/>
  </entry>
</feed>
问题回答

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html


Using NSXMLParser

必须记住,NSXMLParser只是读你依次提供的数据,它没有使用OM结构。

Setup

主要是,你们需要给你们的教职! 举例来说,我从这个支部获得资源,将其转换到NSData。 但是,还有另一个选择:<编码>initWithContentsOfURL。 确保你不要忘记你代表!

-(void) parse
{
    NSString *file = @"myXMLFile.xml";
    NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[file stringByDeletingPathExtension] ofType:[file pathExtension]]];
    //If you already have a string:
    //NSData* data=[xmlString dataUsingEncoding:NSUTF8StringEncoding];
    if (data.length == 0)
    {
        //No data
        return nil;
    }

    ...
}

NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];

Parsing

-(void) parserDidStartDocument:(NSXMLParser *)parser
{
   //Here you set up any variables you might need while parsing
}

-(void) parserDidEndDocument:(NSXMLParser *)parser
{
   //I usually don t have to do anything here but you might need to release some variables here for example.
}

-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    //Here is where the bulk of the parsing is done if you are using attributes. I prefer to use attributes as it looks cleaner both in the XML file and the parser.
    if ([elementName isEqualToString:@"element1"])
    {
        //Just an example of what you might want to do
        int index = [[attributeDict valueForKey:@"attribute1"] intValue];
        NSString *name = [attributeDict valueForKey:@"n"];
        [exampleDictionary setValue:name forKey:[NSString stringWithFormat:@"%d", index]];
    }
    if ([elementName isEqualToString:@"element2"])
    {
        //We need to know that the next piece of information (from foundCharacters) is for element 2
        currentElement = ELEMENT_2;
    }

}

//If you haven t used attributes you might find that you have a lot of parsing to do here instead.
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{ 
    //Check what this info is for?
    if(currentElement == ELEMENT_2)
    {
        element2Data = [NSString stringWithString:string];
    }
}

-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{    
    if ([elementName isEqualToString:@"element2"])
    {
        myObject.somethingThatNeedsElement2 = element2;
    }
}

Finishing

在完成这项工作之后,我们有一个好的想法,即检查任何东西都不会错过,并释放教区记忆。 因此,在您的<代码>parse方法中,在打电话到后添加这一条。

if ([parser parserError] != nil)
{
    [[[[UIAlertView alloc] initWithTitle:@"Error parsing XML" message:[[parser parserError] localizedDescription] delegate:nil cancelButtonTitle:@"Done" otherButtonTitles:nil] autorelease] show];
}
[parser release];

the other option is to use GDataXmlParser (search on google, ready files). u just have to pass tag and it will return you dictionary.





相关问题
List Contents of Directory in a UITableView

I am trying to list the contents of Ringtones directory in a TableView, however, I am only getting the last file in the directory in ALL cells, instead of file per cell. This is my code: - (...

iPhone NSUserDefaults persistance difficulty

In my app i have a bunch of data i store in the NSUserdefaults. This information consists of an NSObject (Object1) with NSStrings and NSNumbers and also 2 instances of yet another object (Object2). ...

Writing a masked image to disk as a PNG file

Basically I m downloading images off of a webserver and then caching them to the disk, but before I do so I want to mask them. I m using the masking code everyone seems to point at which can be found ...

Resize UIImage with aspect ratio?

I m using this code to resize an image on the iPhone: CGRect screenRect = CGRectMake(0, 0, 320.0, 480.0); UIGraphicsBeginImageContext(screenRect.size); [value drawInRect:screenRect blendMode:...

Allowing interaction with a UIView under another UIView

Is there a simple way of allowing interaction with a button in a UIView that lies under another UIView - where there are no actual objects from the top UIView on top of the button? For instance, ...