Jac*_*ill 9 xml iphone objective-c nsxmlparser ios
我有一个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>
Run Code Online (Sandbox Code Playgroud)
如果我制作了4个数组,一个用于名称,一个用于价格,一个用于购买,一个用于描述,如何将数据输入数组?
我想使用的NSXMLParser,但不能得到name,price,where或说明.
我一直坚持如何做到这一点.
任何帮助赞赏.
Red*_*ing 15
首先,您需要创建一个进行解析的对象.它将实例化NSXMLParser实例,将其自身设置为解析器的委托,然后调用解析消息.它还可以负责存储您的四个结果数组:
NSXMLParser * parser = [[NSXMLParser alloc] initWithData:_data];
[parser setDelegate:self];
BOOL result = [parser parse];
Run Code Online (Sandbox Code Playgroud)
您最感兴趣在委托对象中实现的消息是didStartElement.为XML文件中的每个元素调用此人.在此回调中,您可以将名称,价格和where属性添加到各自的数组中.
- (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
}
Run Code Online (Sandbox Code Playgroud)
要获取标签之间的值(例如,“这是第一个产品”。),您可以覆盖-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string