I have XML sample:
<book id="bk101">
<title>XML Developer's Guide</title>
</book>
<book id="bk102">
<title>Midnight Rain</title>
</book>
How can I output title value for book with id "bk101"?
My code:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"book"])
{
NSString *codeValue = [attributeDict objectForKey:@"id"];
if ([codeValue isEqualToString:@"bk101"]) {
//NSLog(@"found"); // output book title here
}
}
}
Suppose structure XML such as in the example and tag has no child elements and text inside the tag does not have unicode or other special characters. Then for output to console (for example) "title" value for book with id "bk101" you should:
Declare codeValue
as property.
@property (strong, nonatomic) NSString *codeValue;
Change your code like below:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"book"])
{
_codeValue = [attributeDict objectForKey:@"id"];
}
}
Add implementation foundCharacters:
method like below:
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if ([_codeValue isEqualToString:@"bk101"])
{
NSLog(@"found: %@", string); // output book title here
}
}
Add implementation didEndElement:
method like below (selectively for the case where not all tags "book" will have an attribute):
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if (_codeValue != nil)
{
_codeValue = nil
}
}
NOTE: If the conditions specified in the beginning of the post will be different - you may need a different implementation.
As alternative you can use XMLConverter and convert your XML (I did some changes):
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="bk101">
<title>XML Developer's Guide</title>
</book>
<book id="bk102">
<title>Midnight Rain</title>
</book>
</books>
to NSDictionary
like below:
2013-12-24 13:15:48.167 test[603:70b] {
books = {
book = (
{
"-id" = bk101;
title = "XML Developer's Guide";
},
{
"-id" = bk102;
title = "Midnight Rain";
}
);
};
}
and work with it.