Ipad XML parsing doubts
my requirement is par开发者_运维百科se an xml file and display it in ipad.But i was totally confused how to parse this xml file,i am novice in xml parsing. kindly help me how to create array for it and how to display in ipad.Its a magazine news application ,any source code or sample applicatiom may help me.
There is a built in XML parsing class in iOS called NSXMLParser
. As an init
parameter it takes an NSData
that is usually the data you get back from a web service. Assign yourself as its delegate and call [parser parse]
and it will call your delegate when it encounters an element, when it finishes an element, etc. See documentation for the parser and its delegate protocol.
If you have control over the structure of your XML, I've found it easier when it's structured like this:
<Element attr1='value1' attr2='value2' />
instead of:
<Element>
<attr1>value1</attr1>
<attr2>value2</attr2>
</Element>
The reason is that the callback for when it finds an element is:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
where attributes
is a dictionary of the values, so in the above example, [attributes objectForKey:@"attr1"]
would give you "value1" if it was structured in the first way. If it's the second way, you end up doing lots of state management that's a bit of a pain, especially if you've got elements within elements, etc.
In addition to NSXMLParser
thare are open-source parsers that either do everything themselves or wrap the built-in parser. I've written my own wrapper for it before. See here for a post on the subject (thanks to this question for the link).
精彩评论