I am using GDataXML to parse may XML, but i have a probleme with this :
<....
<images xmlns:a="http://.../Arrays">
<a:string>http://images...233/Detail.jpg</a:string>
<a:string>http://images....233/Detail2.jpg</a:string>
</images>
.../>
i would like to have all the URL of my images and put it in an NSArray,i am doing like this :
NSError *error = nil;
GDataXMLDocument *xmlResult = [[GDataXMLDocument alloc] initWithData:data options:0 error:&error];
if (error) {
NSLog(#"%#",error);
}
.......
NSArray *array = [... nodesForXPath:#"images" namespaces:a error:&error];
my array it's not null
Now i would like to access my url of images but i can not, i am doing like this:
arrar = [array elementsForName:#"a"];
byt my array is null, i think that the problemm is with namespaces wut i don't konw how to resolve it
Thanks for your answer
I think this question is related to this: parse xml with namespaces with gdata xml. Checkout my answer. Hope it helps! :)
Related
I need to send an NSArray to the server in the JSON array format. How can I convert it to JSON. This is a sample of my NSArray that I have to pass.
array([0] => array('latitude'=>'10.010490',
'longitude'=>'76.360779',
'altitude'=>'30.833334',
'timestamp'=>'11:17:23',
'speed'=>'0.00',
'distance'=>'0.00');
[1] => array('latitude'=>'10.010688',
'longitude'=>'76.361378',
'altitude'=>'28.546305',
'timestamp'=>'11:19:26',
'speed'=>'1.614',
'distance'=>'198.525711')
)`
and the required format is like this
[
{ "latitude":"10.010490",
"longitude":"76.360779",
"altitude":"30.833334",
"timestamp":"11:17:23",
"speed":"0.00",
"distance":"0.00"
},
{
"latitude":"10.010688",
"longitude":"76.361378",
"altitude":"28.546305",
"timestamp":"11:19:26",
"speed":"1.614",
"distance":"198.525711"
}
]
Any one have solution? Thanks in advance.
NSDictionary *firstJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"10.010490", #"latitude",
#"76.360779", #"longitude",
#"30.833334", #"altitude",
#"11:17:23", #"timestamp",
#"0.00", #"speed",
#"0.00", #"distance",
nil];
NSDictionary *secondJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"10.010490", #"latitude",
#"76.360779", #"longitude",
#"30.833334", #"altitude",
#"11:17:23", #"timestamp",
#"0.00", #"speed",
#"0.00", #"distance",
nil];
NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr addObject:firstJsonDictionary];
[arr addObject:secondJsonDictionary];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
The simplest and best approach !!!
To convert NSArray or NSMutableArray into jsonString you can first convert it into NSData and then further convert that into a NSString. Use this code
NSData* data = [ NSJSONSerialization dataWithJSONObject:yourArray options:NSJSONWritingPrettyPrinted error:nil ];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
It helped me and hope it helps you as well. All the best.
I would recommend the SBJson-Framework.
Converting an NSMutableArray is as simple as NSString *jsonString = [yourArray JSONRepresentation];
Edit: Jack Farnandish is right u have to transform it into a NSDictionary before you can convert it to Json. In my example the NSMutableArray has to contain the Dictionary. The Array is only needed to create the square brackets at the beginning and the end of the string.
You can use the build in JSON functions of iOS or use an external lib e.g. JSONKit to convert your data to JSON
First You must change you structure into NSDictionary class and NSArray containing NSDictionary objects, then try JSONKit in iOS 5 serialization works better than standard NSJSONSerialization.
#import <JSONKit/JSON.h>
NSArray *array = // Your array here.
NSString *json = [array JSONString];
NSLog(#"%#", json);
JSONKit performs significantly better than SBJson and others in my own and the author's benchmarks.
Check this tutorial, JSON in iOS 5.0 was clearly explained (serailization, deserailization).
Is the service you are calling a RESTful service?
If so, I'd strongly recommend using RestKit. It does object serialization/deserialization. It also handles all the networking underpinnings. Extremely valuable, and well maintained.
i have a problem parsing my json data for my iPhone app, I am new to objective-C. I need to parse the json and get the values to proceed. Please help. This is my JSON data:
[{"projId":"5","projName":"AdtvWorld","projImg":"AdtvWorld.png","newFeedCount":"0"},{"projId":"1","projName":"Colabus","projImg":"Colabus.png","newFeedCount":"0"},{"projId":"38","projName":"Colabus Android","projImg":"ColabusIcon.jpg","newFeedCount":"0"},{"projId":"25","projName":"Colabus Internal Development","projImg":"icon.png","newFeedCount":"0"},{"projId":"26","projName":"Email Reply Test","projImg":"","newFeedCount":"0"},{"projId":"7","projName":"PLUS","projImg":"7plusSW.png","newFeedCount":"0"},{"projId":"8","projName":"Stridus Gmail Project","projImg":"scr4.png","newFeedCount":"0"}]
On iOS 5 or later you can use NSJSONSerialization. If you have your JSON data in a string you can do:
NSError *e = nil;
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
Edit To get a specific value:
NSDictionary *firstObject = [jsonArray objectAtIndex:0];
NSString *projectName = [firstObject objectForKey:#"projName"];
I would recommend using JSONKit library for parsing.
Here's a tutorial on how to use it.
You will basically end up with a dictionary and use objectForKey with your key to retrive the values.
JSONKit
or
NSJSONSerialization(iOS 5.0 or later)
I have had success using SBJson for reading and writing json.
Take a look at the documentation here and get an idea of how to use it.
Essentially, for parsing, you just give the string to the SBJsonParser and it returns a dictionary with an objectForKey function. For example, your code might look something like:
NSDictionary* parsed = [[[SBJsonParser alloc] init] objectWithString: json];
NSString* projId = [parsed objectForKey:#"projId"];
Use SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *dicRes = [parser objectWithString:stringFromServer error:nil];
No need to use third party classes. Objective-c already includes handling JSON.
The class NSJSONSerialization expects an NSData object or reads from a URL. The following was tested with your JSON string:
NSString *json; // contains your example with escaped quotes
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments error:&error]
For more options with NSJSONSerialization see the documentation.
I'm quite new to programing and have a problem. I have been using touchxml for parsing and there hasn't been any problem before. Now i want to parse an xml string.
I've looked all over the internet but can't find the answer.(i've never done initWithXMLString before maybe i'm doing something wrong here?)
My current code for parsing:
NSArray *resultNodes = NULL;
CXMLDocument *rssParser = [[CXMLDocument alloc] initWithXMLString:str options:0 error:nil];
NSString *strName;
resultNodes = [rssParser nodesForXPath:#"//FictionBook" error:nil];
NSLog(#"RESULT NODE COUNT =%d",[resultNodes count]);
and my string looks like this:
"<?xml version="1.0" encoding="UTF-8"?>
<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>prose_contemporary</genre> <author><first-name>Мария</first-name><last-name>Метлицкая</last-name><id>f97cbf85-bb7c-102b-8639-bb1d5f8374bd</id></author><book-title>Наша маленькая жизнь (сборник)</book-title> <annotation><p>Мария Метлицкая рассказывает о простых людях – они не летают в космос, не блистают на подмостках сцены, их не найдешь в списке Forbеs.</p></annotation></description></title-info></FictionBook>"
xml apears to be valid, I've checked about 10 xml validators.
But i get 0 from [resultNodes count].
Anybody encountered something similar before?
Thanks in advance!
Try to check if there were an error while parsing:
NSError *error;
NSArray *resultNodes = NULL;
CXMLDocument *rssParser = [[CXMLDocument alloc] initWithXMLString:str options:0 error:&error];
NSLog("Error: %#",error);
Also does your XML contains elements with namespaces?
Firstly get you xml validate or not by this http://www.xmlvalidation.com/ and if it validated then you are not getting any response then you should check the error code what the error is thrown by the xml parser and then try to check by error code what is the problem.
I need quick help
structure of xml is like this
<VacancyList generated="2011-08-26T09:06:13" xsi:schemaLocation="http://www.abc.com/dtd/vacancy-list.xsd"><Vacancy id="157890" date_start="2010-10-12" date_end="2011-12-31" reference_number=""><Versions><Version language="nb">
and I am using KissXML like this
DDXMLDocument *theDocument = [[DDXMLDocument alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://pwc.easycruit.com/export/xml/vacancy/list.xml"]] options:0 error:&error];
NSArray* resultNodes = nil;
resultNodes = [theDocument nodesForXPath:#"Versions" error:&error];
but results is always blank.
Please help me with this
XML is case sensitive. You are looking for "versions" in your xpath query and not "Versions" (which is what exists in your document). I think that is your problem.
I am stuck with some TouchXML code. Please help.
I have the following code to get the data from an xml webservice:
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"String data: %# \n", data);
//Do the parsing
CXMLDocument *document = [[[CXMLDocument alloc] initWithData:urlData encoding:NSUTF8StringEncoding options:0 error:&error] autorelease];
NSLog (#"Document :%# \n",[document stringValue]);
The string data does have the content from the service, but how come the CXMLDocument object does not contain anything? Someone can tell me why?
2009-12-30 18:21:59.467 MyAdvancedBlog[3425:207] String data: <?xml version="1.0" encoding="utf-8"?>
<Post xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<IdPostazione>42</IdPostazione>
<StringID>HOANG</StringID>
<Name>CASSA2</Name>
<TerminalValid>true</TerminalValid>
<NeedSession>false</NeedSession>
</Post>
2009-12-30 18:21:59.469 MyAdvancedBlog[3425:207] Document :(null)
TouchXML's documentation says that CXMLDocument should act just like NSXMLDocument. So, the reference for initWithData:options:error: might help.
It says the result will be nil if it's unsuccessful, and error will then contain more info. Is it nil?
You might consider using NSXMLDocument for the moment, and see if they really do act the same. If they don't, file a bug with TouchXML.
You could also use initWithXMLString:options:error: along with that string you already decoded.
Edit: Even better. Here's example code for using NSXMLDocument. In theory, it should work for CXMLDocument as well.