I am creating an iPhone App in which I have to consume values from a service url.The response from url is of XML format.XML file has same name attributes many times,and those attributes are not static.I mean the no of attributes may increase from time to time. So I couldn't understand how to consume that XML response in iPhone.
My XML response looks like this :
GetUserResponse xmlns="http://schemas.datacontract.org/2004/07"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<CompanyList>
<User>
<Address>
<City>Alabaster</City>
<State>Alabama</State>
</Address>
<Employee>
<Name>DrJohn</Name>
</Employee>
</User>
<User>
<Address>
<City>SanFransisco</City>>
<State>California</State>
</Address>
<Employee>
<Name>DrWilliams</Name>
</Employee>
</User>
</CompanyList>
</GetUserResponse>
The thing is I couldn't say there will be specific number of tags as of 2 tags here.They may or may not increase from time to time.I think we should take something like count number of items and extract the values but couldn't understand how?
This is one of many ways to do it. You can simply get the attributeDict and parse all the values from it using key-value.
NSString *element;
- (void) viewDidLoad {
[super viewDidLoad];
cityArr = [[NSMutableArray alloc] init];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
element = elementName;
if ([elementName isEqualToString:#“Address”]) {
// initialize stings to store values of child elements
cityStr = [NSMutableString alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([element isEqualToString:#“City”])
cityStr appendString:string];// Append Values
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#“Address”]) {
[cityArr addObject:cityStr]; // Add strings to array/dictionary and release string
}
}
I have continuous tags of img id="#", where # varies from 1 to 9.
The description of tags consists of floating values.
When I use the standard NSXML Parser, i not getting all the values.
My XML for reference:
<img id="1">-0.0111328,-0.0635608,0.152549,0.11211,-0.0250431,
-0.0370875,0.0862391,0.0970791,-0.0195908,
-0.00892297,0.0791795,0.0554013,0.00362028,0.0138572,0.0432729,
0.0253036,-0.0770325,0.14065,0.118424,0.1787,
0.0734354,0.160883,0.101831,0.237038,0.0681151,0.178331,
0.106532,0.224731,0.133766,0.222096,0.165214,0.240752,
-0.0280366,0.106239,0.052094,0.110642,
</img>
How would I parse the above XML?
Kindly, help me out.
Thanx
This is because parser:foundCharacters: does not deliver all characters at once. You need to concatenate all strings that you get between the callbacks of the parser:didStartElement:namespaceURI:qualifiedName:attributes: and parser:didEndElement:namespaceURI:qualifiedName: that you get for the <img> tag.
In the code below, buf is an NSMutableString ivar of your parser delegate.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
if ([qualifiedName isEqualToString:#"img"]) {
buf = [NSMutableString string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([qualifiedName isEqualToString:#"img"]) {
buf = [buf stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"Got %#", buf);
}
}
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[buf appendString:string];
}
Finally got it... i placed start and end tags for img id = '#'. My structure now looks like this:
<images>
<img id = '1'> -0.0111328,-0.0635608,0.152549,0.11211,-0.0250431,
-0.0370875,0.0862391,0.0970791,-0.0195908,
-0.00892297,0.0791795,0.0554013,0.00362028,0.0138572,0.0432729,
0.0253036,-0.0770325,0.14065,0.118424,0.1787,
0.0734354,0.160883,0.101831,0.237038,0.0681151,0.178331,
0.106532,0.224731,0.133766,0.222096,0.165214,0.240752,
-0.0280366,0.106239,0.052094,0.110642, ....
</img>
<img id = '2'> ...
</img>
....
....
</images>
<mapping>
<map>
<imgid> 1 </imgid>
<keyword> heavy </keyword>
</map>
<map>
<imgid> 2 </imgid>
<keyword> metal </keyword>
</map>
...
...
</mapping>
Placing start and end tags allowed me to parse the whole xml.
Earlier, the start and end tags were for individual images which only resulted in parsing of one img.
This made me add another key point while parsing XML.
Hope this helps others as well.
How can I get some data from the tag of a xml file?
I have a tag like this:
`<link href="http://127.0.0.1:8580/directory/playlists/" rel="alternate" type="application/atom+xml;type=feed" />`
I would like to save the http link: http://127.0.0.1:8580/directory/playlists/
Can I use the NSXMLParser?
Thanks a lot!
You need to implement a delegate for the NSXMLParser that conforms to the NSXMLParserDelegate protocol. In this implementation implement at least this method:
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"link"]) {
NSString* href = [attributeDict objectForKey:#"href"];
// Do you stuff with the href
}
}
The value you are after "http://127.0.0.1:8580/directory/playlists/" is called an attribute. It is the attribute of the element "link".
Check out the Apple documentation relating to XML processing and elements and attributes. For example, http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/XMLParsing/Articles/HandlingElements.html
I am currently working on a software to control aMule status of my server through the iPhone,
i created a socket that spits out xml which should be parsed out, but because NSXMLParser is event-drive, i'm having problems in understanding how this could work...
I thought of this type of XML structure, if you have ideas of a better way to structure it please tell me!! :D
<root type="donwloads"> <-- specifies downloads or search results
<file name="Ubuntu_9_10.iso" status="[11,6%]" />
<file name="Fedora 12.iso" status="[56,2%]" />
</root>
What i was thinking is, as i want to put this in a tableview, most probably i will need a NSMutableArray with lots of NSDictionaries based on the results, every dict should be a file.. what do you guys propose?? how should i handle this situation?
Thanks
Write a parser class that turns nodes into Core Data managed objects and saves them to the managed object context, when a parser callback event is fired.
Use an NSFetchedResultsController to access the Core Data store. As the managed objects come in and are saved, the results controller updates the table view with whatever results it fetches.
An NSMutableArray of NSDictionary seems like a reasonable approach for your in-memory data structure.
You'll basically have a series of callbacks that build up that array as NSXMLParser runs through your XML file:
- (void) parseXML:(NSString *) filename {
NSURL *xmlURL = [NSURL fileURLWithPath:filename];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[xmlParser setDelegate:self];
[xmlParser parse];
// Check for errors.
NSError *errorCode = [xmlParser parserError];
if (errorCode) {
// handle error here
NSLog(#"%#", [errorCode localizedDescription]);
}
[xmlParser release];
}
And your main delegate:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
// If certain elements are found initialize the object
if ([elementName isEqualToString:"#file"]) {
NSMutableDictionary *currentFile = [[NSMutableDictionary alloc] init];
// Look through the attributes add stuff to your dictionary
// Add it to your array.
}
}
Since all of your data is returned in attributes you can do it this way. Otherwise you'd need to store the file and build it up (the foundCharacters delegate) finally adding it to your array when the file's tag occurs in the didEndElement delegate.
Thanks a lot for your answers :D fortunately i resolved the problem 10 minutes after :D
ill post what i did:
XML:
<root>
<downloads>
<file type="text" name="fdsdf" />
<file type="text" name="sdfsdfssds" />
</downloads>
</root>
NSXMLParser delegates:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
if([elementName isEqualToString:#"downloads"] || [elementName isEqualToString:#"results"]){
NSLog(#"starting or downloads or results");
if(xmlArray){
xmlArray= nil;
}
self.xmlArray= [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:#"file"]){
NSLog(#"found file...");
[self.xmlArray addObject:attributeDict];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if([elementName isEqualToString:#"downloads"] || [elementName isEqualToString:#"results"]){
if([elementName isEqualToString:#"downloads"]){
NSLog(#"downloads found: %#... reloading table", xmlArray);
}
}
}
I hope this can possibly help someone which has my same problem :D
In my iPhone application, I have the following NSString:
NSString *myxml=#"<students>
<student><name>Raju</name><age>25</age><address>abcd</address>
</student></students>";
How would I parse the XML content of this string?
Download:
https://github.com/bcaccinolo/XML-to-NSDictionary
Then you simply do :
NSDictionary *dic = [XMLReader dictionaryForXMLString:myxml error:nil];
Result is a NSDictionary *dic with dictionaries, arrays and strings inside, depending of the XML:
{
students = {
student = {
address = abcd;
age = 25;
name = Raju;
};
};
}
You should use the NSXMLParser class
Here's a link to the documentation for that class:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html
Your code should look something like this:
#implementation MyClass
- (void)startParsing {
NSData *xmlData = (Get XML as NSData)
NSXMLParser *parser = [[[NSXMLParser alloc] initWithData:xmlData] autorelease];
[parser setDelegate:self];
[parser parse];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
NSLog(#"Started %#", elementName);
}
Another answer is: Don't use XML. Use a plist instead, which is written using XML but more easily parsable in Objective-C into distinct data types (NSArray for example has a method to convert a file or NSData plist into an NSArray).
Like #Jon Hess mentioned, just create a wrapping class for the "optional" methods of the NSXMLParserDelegate. These methods help you separate the tasks that you might find useful when you parse your xml.
One really good online journal file I found is Elegant XML parsing with Objective-C. Phil Nash really took his time to show the basics of the parsing options at your reach. It can take a new programmer and guide him/her through the whole setup.
Loading the xml can be a modification of #Jon Hess method.
You can setup the:
-(void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict{
}
to handle events on certain elements.
Also implement the:
-(void)parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string {
}
to place the strings found into a collection of objects.
I think the best equivalent to XMLDocument is AbacigilXQ Library. You should look at it. I'm using it.
http://code.google.com/p/abacigilxq-library/