使用NSXMLParser解析XML文件 - 获取值 [英] Parsing XML file with NSXMLParser - getting values

查看:274
本文介绍了使用NSXMLParser解析XML文件 - 获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文件,其中包含我想要使用的一些数据:

I've got a XML file which contains some data I would like to use:

<?xml version="1.0" encoding="UTF-8" ?>

<items>
<item name="product" price="19.95" where="store">
This is the first product.
</item>

<item name="product2" price="39.95" where="online">
This is the second product.
</item>

<item name="product3" price="99.95" where="garagesale">
This is the third product.
</item>

</items>

如果我制作了4个数组,一个用于名称,一个用于价格,一个用于它的位置买了一个用于描述,如何将数据输入数组?

If I made 4 arrays, one for the name, one for the price, one for where it was bought and one for its description, how would I get the data into the arrays?

我想使用NSXMLParser,但无法获得 name 价格其中或说明。

I figured using NSXMLParser, but couldn't get name, price, where or the description.

我坚持如何做到这一点。

I'm stuck on how to do this.

任何帮助表示感谢。

推荐答案

首先,您需要创建一个进行解析的对象。它将实例化 NSXMLParser 实例,设置本身作为解析器的委托,然后调用解析消息。它还可以负责存储您的四个结果数组:

First you need to create an object that does the parsing. It will instatiate the NSXMLParser instance, set itself as the delegate for the parser and then call the parse message. It can also be responsible for storing your four result arrays:

NSXMLParser * parser = [[NSXMLParser alloc] initWithData:_data];
[parser setDelegate:self];
BOOL result = [parser parse];

您最感兴趣在委托对象中实现的消息是didStartElement 。为XML文件中的每个元素调用此人。在此回调中,您可以添加您的姓名,价格和广告。 where属性到各自的数组。

The message you are most interested in implementing in your delegate objects is didStartElement. This guy gets called for each element in your XML file. In this callback you can add your name, price & where attributes to their respective arrays.

- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qualifiedName
    attributes:(NSDictionary *)attributeDict
{
    // just do this for item elements
    if(![elementName isEqual:@"item"])
        return;

    // then you just need to grab each of your attributes
    NSString * name = [attributeDict objectForKey:@"name"];

    // ... get the other attributes

    // when we have our various attributes, you can add them to your arrays
    [m_NameArray addObject:name];

    // ... same for the other arrays
}

这篇关于使用NSXMLParser解析XML文件 - 获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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