使用 NSXMLParser 解析 XML 文件 - 获取值
我有一个 XML 文件,其中包含一些我想使用的数据:
<?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 个数组,一个用于名称,一个用于价格,一个用于购买地点,一个用于描述,我将如何获得数据存入数组?
我想使用 NSXMLParser,但无法获取 name
、price
、where
或描述。
我不知道如何做到这一点。
任何帮助表示赞赏。
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>
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?
I figured using NSXMLParser, but couldn't get name
, price
, where
or the description.
I'm stuck on how to do this.
Any help appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,您需要创建一个执行解析的对象。它将实例化 NSXMLParser 实例,设置本身作为解析器的委托,然后调用解析消息。它还可以负责存储四个结果数组:
您最有兴趣在委托对象中实现的消息是 didStartElement。这个人会因 XML 文件中的每个元素而被调用。在此回调中,您可以添加您的姓名、价格和价格。其中属性到各自的数组。
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:
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 *)parserfoundCharacters:(NSString *)string
To get the value between the tags (e.g. "This is the first product.") you can override - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
在下面的方法中
in the follwing method
您必须将项目标签的字典视为一个数组,并将三个标签(名称、价格和位置)视为索引 0,1,2 处的对象
you have to consider the dictionary of item tag as an array and three tag (name,price and where)as the object at index 0,1,2