libxml2 example (with wrapper) - iphone

I am using the XML parser libxml2 with wrapper as given on the page
http://cocoawithlove.com/2008/10/using-libxml2-for-parsing-and-xpath.html
But i am not sure if I am using correctly and am getting errors (parsing,etc)
So could someone please provide me a complete example which i can refer and get an idea if I am doing something incorrectly.
thanks a lot for all your help in advance.

I'm using this methods too, to parse xml and html files.
For example to parse rss xml:
//add xml source
NSURL *url = [NSURL URLWithString:#"http://feeds.bbci.co.uk/news/rss.xml?edition=int"];
NSData *xmlData = [NSData dataWithContentsOfURL:url];
//parse the whole file with all tags
NSArray *rssFeedArray = PerformXMLXPathQuery(xmlData, #"//*");
NSLog(#"rssFeedArray: %#", rssFeedArray);
//* - query means the parser will go through all tags of the file. Then log the array to see the whole structure of xml.
Whith '/rss/channel/item' query you will only get the item tags element's, (or to get only the first item use '/rss/channel/item[1]').
in this case because of the bbc feed structure you can catch each item title at
[[[[rssFeedArray objectAtIndex:i] valueForKey:#"nodeChildArray"] objectAtIndex:0] valueForKey:#"nodeContent"]]
and description at
[[[[rssFeedArray objectAtIndex:i] valueForKey:#"nodeChildArray"] objectAtIndex:1]valueForKey:#"nodeContent"]]
and go on and on.

Related

How to save data into an XML file

My application contains 8 TextFields. When I click the submit button I want to save all the values from the TextFields into an XML file (and generate a XML file if required). How can I do this?
Another XML writer which will get the job done is XSWI (shameless plug - I wrote that code).
There are many ways you could do this. One quick and dirty way of doing it is to generate a string in your code and insert the values
e.g.
NSString *myXML = [NSString stringWithFormat:#"<myxml><value1>%#</value1><value2>%#</value2></myxml>", textfield1, textfield2];
Then open a file and write myXML to it.
Not very elegant, but it depends on what exactly you want.
Do you need the XML file to be in a specific format? If not the easiest way is to save it as a plist (a type of xml file) by putting your strings into an array and then saving the array as a plist using
NSArray *array = [NSArray arrayWithObjects:label1.text, label2.text, label3.text, etc, nil];
[array writeToFile:fileName atomically:YES];
The nice thing about the plist is that you can easily load the string again by calling:
NSArray *array = [NSArray arrayWithContentsOfFile:filename];
If you need your XML in a different format from what the plist produces, the easiest way is probably just to build the XML yourself using string concatenation, e.g.
NSString *xml = [NSSString stringWithFormat:#"<root><label>%#</label><label>%#</label><label>%#</label>etc</root>", label1.text, label2.text, label3.text, etc];
You can use GDATAXML to read and write XML to file.
Refer this link to see how its done.
http://www.raywenderlich.com/725/how-to-read-and-write-xml-documents-with-gdataxml

Parse XML in iPhone (attributed not separated)

Is there a way to parse an XML in iOS where the attribute are not separated
e.g:
Users
UserId="1" Name="John Smith" Loc="London"
UserId="2" Name="Johnny Cash" Loc="Nashville"
Users
Thanks
It seams like you havent got xml at all. You are missing all usefully symbols that would normally help with the parsing. You taks is to parse a new format specification.
My first bit of advice is to ask whoever is providing you with this feed to put it into a proper format (JSON or plist are the easiest to work with).
Failing this, if the feed is not too big (otherwise you will hit performance issues), parse the feed manually character by character. You probably want to write a event based parser.
Split the feed line by line, perhaps using componentsSeparatedByString:
Then read characters into a string untill you hit an = that string is your key. Next read between the quotes "" That string is your value. FIre the key and the value off to a delegate.
JSON parsing classes will help you out...
NSString *responseString = #""; // your data contained string.
SBJSON *json = [[SBJSON new] autorelease];
NSArray *resultData = [json objectWithString:responseString error:&error];

TBXML root element is null no matter what I do

Wracking my brain for hours trying to figure this one out. TBXML must have the rootXMLElement set in order to begin traversing and parsing data.
No matter what I do, when I NSLog it, it's null.
Here's a sample of the XML:
<?xml version= "1.0" encoding="UTF8"?>
<patients>
<patient>
<patientNumber>1234</patientNumber>
<nameFirst>Jason</nameFirst>
<!--more properties of a patient-->
</patient>
<patient>
<patientNumber>5542</patientNumber>
<nameFirst>Gary</nameFirst>
<!--more properties of a patient-->
</patient>
</patients>
The code I'm using thus far:
NSURL *xmlURL = [NSURL URLWithString:destPath];
TBXML *tbxml = [TBXML tbxmlWithURL:xmlURL];
NSLog shows tbxml.rootXMLElement as null.
Other details of note:
I use a ruby script to delete any non-ASCII characters from the XML file. The app does not require anything more.
I thought the problem might be that the XML file was not UTF-8, so I used bash command iconv to convert it from ASCII to UTF-8. Didn't work either.
Any suggestions are greatly appreciated.
It looks like it is a local XML based on the fact that you are preprocessing it. When you are processing local file paths as URLs you need to use fileURLWithPath: for it to work properly. So you need to do this,
NSURL *xmlURL = [NSURL fileURLWithPath:destPath];
TBXML *tbxml = [TBXML tbxmlWithURL:xmlURL];

Represent XML content as NSData - iPhone

I have an external XML file which I want to be represented in an NSData object
I am doing this;
NSError *error;
NSString* contents = [NSString stringWithContentsOfUrl:[NSURL URLWithString:#"http://www.apple.com/"]
encoding:NSUTF8StringEncoding
error:&error];
NSData* xmlData = [contents dataUsingEncoding:NSUTF8StringEncoding];
But for some reasons, I am getting an error (does not respond)
Please help me.
Don't have time to test this out but I think you may want to try looking into NSData's dataWithContentsOfURL: or dataWithContentsOfURL:options:error: and get it directly as data.
Also, unless you just threw http://www.apple.com/ in as a placeholder, I don't believe the source of that page is valid XML. The following feed is valid xml: https://stackoverflow.com/feeds You could try that. with what you have now first and see if it works.
Hope this helps.
Updated:
Without my knowing your project, you may get some benefit from using TouchXML - https://github.com/mrevilme/TouchXML which handles XML very well including what you are trying to do:
CXMLDocument *xmlDoc = [[CXMLDocument alloc] initWithContentsOfURL:(NSURL *)inURL encoding:(NSStringEncoding)encoding options:(NSUInteger)inOptions error:(NSError **)outError];

get element value

I have a NSString like that? (in iPhone application)
NSString *xmlStr = "<?xml version=1.0 encoding=UTF-8>
<information>
<name>John</name>
<id>435346534</id>
<phone>045635456</phone>
<address>New York</address>
</information>"
How I can get elements value?
(Do i need convert to XML format and get elements value? or split string? any way please tell me?)
Thank you guys.
If you want to use split string, you can use tokenization of strings using "componentsSeparatedByString" method. This is a more cumbersome method of course, rather than the recommended XMLParser
To get the name.
NSArray *xmlStr_first_array = [xmlStr componentsSeparatedByString: #"<name>"];
NSString *xmlStr_split = [NSString stringWithFormat:#"%#",[xmlStr_first_array objectAtIndex:1]];
NSArray *xmlStr_second_array = [xmlStr_split componentsSeparatedByString: #"</name>"];
NSString *name = [NSString stringWithFormat:#"%#",[xmlStr_second_array objectAtIndex:0]];
The most obvious solution is to use an XML parser to retrieve the values from each element.
You could use the excellent TBXML for this task. It provides a really simple interface where it wouldn't take more than a few lines to retrieve the desired values. The drawback to using this small library is that it (as far as I know) loads the entire XML data into memory. In this particular case, however, that is not problem at all.
There's of course also the option of using the NSXMLParser, though this is an event-driven parser, and thus a bit less simple to use.
Your string is in xml format already and you need to parse it to retrieve data. There're several options available - for example you can use NSXMLParser class or libxml library.
Edit: XMLPerformance sample project shows how to use both approaches and compare their performance.