可能重复:
NSXMLParser on iOS, how do I use it given a xml file
Cocoa/Objective-C : Best Practice to parse XML Document?
我想在Cocoa Application中解析XML文件。但是xml的解析器没有工作。请帮助解析此文件或其他类似的xml文件。我的Xml文件如下:
<book name="Genesis">
<chapter number="1">
<verse number="1">At the first God made the heaven and the earth.</verse>
<verse number="2">And the earth was waste and without form; and it was dark on the face of the deep: and the Spirit of God was moving on the face of the waters.</verse>
<verse number="3">And God said, Let there be light: and there was light.</verse>
</chapter>
</book>
<book name="Genesis">
<chapter number="1">
<verse number="1">At the first God made the heaven and the earth.</verse>
<verse number="2">And the earth was waste and without form; and it was dark on the face of the deep: and the Spirit of God was moving on the face of the waters.</verse>
<verse number="3">And God said, Let there be light: and there was light.</verse>
</chapter>
</book>
答案 0 :(得分:1)
实际上有两种解析XML的方法 - 事件驱动的方法(例如NSXMLParser使用的方法)和树方法(例如NSXML使用的方法)。
如果你只是在特定元素之后,那么使用NSXML使用的树方法可能要容易得多,因为它可以让你使用XPath(实际上是XQuery)查询XML文档来返回特定的节点,你感兴趣的等等。
如果这听起来像使用NSXMLParser迭代整个结构可能是一种更富有成效的方法,那么我建议阅读the Introduction to Tree-Based XML Programming Guide for Cocoa。 (“查询XML文档”部分应该特别重要。)
答案 1 :(得分:0)
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:@"book"])
{
item = [[NSMutableDictionary alloc] init];
item_name = [[NSMutableString alloc] initWithString:[attributeDict valueForKey:@"name"]];
}
//然后在item_name中,您将值作为Genesis
//尝试像这样解析
编辑:看到评论后
if ([elementName isEqualToString:@"verse"])
{
item_name1 = [[NSMutableString alloc] initWithString:[attributeDict valueForKey:@"number"]];
}
//在item_name1中,您将获得值为1