TouchXML - CXMLDocument object failed to initialize - iphone

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.

Related

how to implements code for get the JSON objects in iphone?

hi all i am a new iphone developer. i am getting response from my required URL as shown in the below here i need to get Name of "CategoryID":1 and Name of "CategoryID":2 both are in separate array sets. how to implements code for get the JSON objects in iphone?. thank you
code for getting response:
theXML = [[NSString alloc] initWithBytes: [RoutData mutableBytes] length:[RoutData length] encoding:NSUTF8StringEncoding];
NSLog(#"---->>>>>>-->>>:%#",theXML);
Response:
LocationTracking[1807:f803] ---->>>>>>-->>>:<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><getGearLockerCategoriesResponse xmlns="http://tempuri.org/"><getGearLockerCategoriesResult><status>SUCCESS</status><errorType /><errorMessage /><jsonString>[{"CategoryID":1,"ItemCount":1,"level":1,"Name":"Boots","Description":"Boots descrition","childs":[{"CategoryID":2,"ItemCount":1,"level":2,"Name":"Cold Water","Description":"Cold Water Description","childs":[]}]}]</jsonString><serverTimestamp>63477507673796</serverTimestamp></getGearLockerCategoriesResult></getGearLockerCategoriesResponse></soap:Body></soap:Envelope>
<jsonString>
[{"CategoryID":1,"ItemCount":1,"level":1,"Name":"Boots","Description":"Boots
descrition","childs":[{"CategoryID":2,"ItemCount":1,"level":2,"Name":"Cold
Water","Description":"Cold Water Description","childs":[]}]}]
</jsonString>
<serverTimestamp>63477390375625</serverTimestamp>
</DiveTravelerResponse>
The Touch JSON library is a good solution: https://github.com/TouchCode/TouchJSON
NSJSONSerialization. If your JSON is in an NSString named 'str':
NSError *jsonError = nil;
NSArray *rootObjectArray = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&jsonError];
if (rootObjectArray)
{
/* you have a foundation object */
}
else
{
/* something went wrong */
NSLog(#"jsonError: %#", [jsonError localizedDescription]);
}

GDataXml and namespaces

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! :)

Can't parse xml with touch xml

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.

iPhone encoding of non latin characters

I am trying to parse a JSON response of a GET request. When the characters, are latin no problem.
However when they are not latin the message doesn't come out correctly. I tried greek and instead of "πανος" i get "& pi; & alpha; & nu; & omicron; & sigmaf;"
The code I use for parsing the response is:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"response %#", responseString);
// array from the JSON string
NSArray *results = [responseString JSONValue];
When I try to read the response from a website using ajax, everything is fine. The same applies when trying to send a GET request to the application servers with data from iphone. So when i transmit data to the server and read it from the website everything is fine. When i try to show the same data in the app, "Houston we have a problem".
Any clues?
EDIT: To avoid misunderstandings, it's not an issue of HTML, I just point out that for some readon utf-8 characters here are encoded correctly and automatically eg. "&pi" will be converted to "π", however objective c doesn't seem to do this on its own
There is a confusion I think.
π is an HTML entity which is unrelated to text encoding like UTF8 / Latin.
Read wikipedia for details about...
You need a parser to decode these entities like the one previously mentioned by Chiefly Izzy:
NSString+HTML category and method stringByReplacingHTMLEntities
Look at Cocoanetics NSString+HTML category and method stringByReplacingHTMLEntities method. You can find it at:
https://github.com/Cocoanetics/NSAttributedString-Additions-for-HTML/blob/master/Classes/NSString%2BHTML.m
Here's a pretty decent list of lot of HTML entities and their corresponding unicode characters.
Try to use this snippet of code:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSString *decodedString = [NSString stringWithUTF8String:[responseString cStringUsingEncoding:[NSString defaultCStringEncoding]]];
NSLog(#"response %#", decodedString);
// array from the JSON string
NSArray *results = [decodedString JSONValue];
I have faced the same problem, but I solved it by changing the JSON parser. I have started using the SBJSONParser, and now I am getting the appropriate results. This is the code snippet, I have used
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
SBJSON *parser=[[SBJSON alloc]init];
NSArray *JSONData = (NSArray*)[parser objectWithString:returnString error:nil];

Parsing SOAP result using TouchXML in iOS SDK (iPad)

I'm working on an iPad project that is using functions in a WebService.
Handling webservice connection, data etc works find. But i'm not able to parse the result SOAP using TouchXML. Getting the nodes out of the xml always returns 0 length.
The output xml:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <LogOnResponse xmlns="http://coreservices.org/v1"> <LogOnResult> <Id>1c0e9ad0-a3be-4cd0-8f0d-0616a63a4e28</Id> <userId>2</userId> <user> <ID>2 <Name>Beheerder <emailAddress /> <cultureName>nl-NL</cultureName> </user> </LogOnResult> </LogOnResponse> </soap:Body></soap:Envelope>
parser code:
NSData *aData = [[NSData alloc] initWithBytes:[webData mutableBytes] length:[webData length]];
NSString *xmlData = [[NSString alloc] initWithData:aData encoding:NSASCIIStringEncoding];
NSLog(#"%#", xmlData);
[xmlData release];
CXMLDocument *domUserIdentity = [[[CXMLDocument alloc] initWithData:aData options:0 error:nil] autorelease];
[aData release];
NSArray *nodesList = [domUserIdentity nodesForXPath:#"//LogOnResult" error:nil]; // 0 length
for (CXMLElement *resultElement in nodesList) {
for (int counter = 0; counter
NSString *elemName = [[resultElement childAtIndex:counter] name];
NSString * elemValue = [[[resultElement childAtIndex:counter] stringValue] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
[elemName release];
[elemValue release];
}
}
[nodesList release];
Any idea what did i do wrong?
Thank's alot in advance.
Inoel
Try using the NSXMLDocument, it should work as well as CXMLDocument. Here are some docs:
link
I recommend using an XPath Parser. You aren't doing anything too heavy, so the speed hit is well worth it. My personal choice is TFHpple. There are slightly faster and more precise solutions out there, but I find TFHpple's simplicity hard to beat.
Example:
NSData *data = [[NSData alloc] initWithContentsOfFile:#"example.html"];
// Create parser
xpathParser = [[TFHpple alloc] initWithXMLData:data];
NSArray *elements = [xpathParser search:#"//LogOnResult"];
TFHppleElement *element = [elements objectAtIndex:0];
// Get the text within the cell tag
NSString *content = [element content];
[xpathParser release];
[data release];
Obviously you'd have to write some code to save the parts you want. Looking at this data, I'd probably make a custom data holder class that you can access with properties. You can parse your XML into that and then save it as a property in the view controller that will be accessing it.
Happy coding!