iPhone 上的 XML 解析
我想为 iPhone 做一些简单的 XML 解析。主要是为了练习。我认为 XML 非常简单,我想学习如何将它与其他语言集成。
我使用此链接来获取有关如何进行 XML 解析的教程,但对于我的目的而言,它有点先进:/
是否有一种简单的方法不需要很多行代码来进行 XML 解析?
致以最诚挚的问候!
克里斯蒂安
编辑:
我能够通过此实现我想要的:
- (void)startParsing {
NSData *xmlData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.vegvesen.no/trafikk/xml/savedsearch.xml?id=604"]];
NSXMLParser *parser = [[[NSXMLParser alloc] initWithData:xmlData] autorelease];
[parser setDelegate:self];
[parser parse];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
NSLog(@"Started %@", elementName);
}
这只会打印出 elementName...我应该如何从这里继续获取每个元素的值?
I wanna do some simple XML parsing for the iPhone. Mostly for practice. I think that XML is really easy and i wanna learn how to integrate it with other languages.
i used this link for a tutorial on how do XML parsing, but it was a little bit to advanced for my purpose :/
isn't there a simple way that does not require many lines of code to do XML parsing?
Best regards!
Kristian
EDIT:
I was able to achieve what i wanted with this:
- (void)startParsing {
NSData *xmlData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.vegvesen.no/trafikk/xml/savedsearch.xml?id=604"]];
NSXMLParser *parser = [[[NSXMLParser alloc] initWithData:xmlData] autorelease];
[parser setDelegate:self];
[parser parse];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
NSLog(@"Started %@", elementName);
}
this will just print out the elementName... how should i go on from here to get the value from each element?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然知道这一点很好,但实际上,使用 JSON 可能会更轻松
While it's good to know, in practice you might have a much easier time with JSON
我想你一定已经制作了这样的模型类:
import
CarDetails.h
CarDetails.m
import "CarDetails.h"
@implementation CarDetails
@synthesize MapName;
@synthesize MapContentName;
@synthesize地图宽度,地图高度;
@end
看到这些是你全局存储值的模型对象,你可以使用这里的值
现在我们使用三个xml解析器委托
1)在didStart中,只有当你找到第一个节点时,你才会分配模型类对象
2)在foundCharacters中添加数据
3)在didEndElement中,您将把foundCharacters中的数据分配给模型对象
i suppose you must have made a model class like this :
import
CarDetails.h
CarDetails.m
import "CarDetails.h"
@implementation CarDetails
@synthesize MapName;
@synthesize MapContentName;
@synthesize MapWidth,MapHeight;
@end
See these are the model objects where u store ur values globally and you can use the values from here
now we use three xml parser delegates
1) in didStart you will allocate the model class object only if you find the very first node
2) in foundCharacters you append the data
3) in didEndElement you will assigh the data from foundCharacters to the model object