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.
Related
I load XML response from a server and parsed using NSXMLParser. No error in the simulator. But shows NSXMLParserErrorDomain Code=5 in iPhone.
NSString *settings = "http://website.com/settings";
NSURL *url = [NSURL URLWithString:settings];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
xmlParser.delegate = self;
BOOL success = [xmlParser parse];
if(success)
{
NSLog(#"Parse Success");
}else{
NSLog(#"Parse Failure");
NSLog(#"Parse Error: %#",[xmlParser parserError]);
}
XML Response
<?xml version="1.0" encoding="utf-8"?>
<Settings>
<AutoRefereshTime>10</AutoRefereshTime>
<CashierPasswordRequired>Y</CashierPasswordRequired>
<CheckoutTableColor>#FFFF00</CheckoutTableColor>
<CompanyLogo>http://website.com/UCS_WS/Images/Logo/Logo.png</CompanyLogo>
<CompanyName>UnoRestaurant</CompanyName>
<ConfirmedTableColor>008ED5</ConfirmedTableColor>
<Description>The Great Indian Restaurant</Description>
<DevelopedBy>Unipro</DevelopedBy>
<HoldTableColor>A02325</HoldTableColor>
<ImageURL>http://rwebsite.com/UCS_WS/Images/Dish/</ImageURL>
<isCategoryEnabled>Y</isCategoryEnabled>
<isOtherLanguageEnabled>Y</isOtherLanguageEnabled>
<NormalTableColor>#0000FF</NormalTableColor>
<OrderScreenView>POS View</OrderScreenView>
<OtherLanguage>Tamil</OtherLanguage>
<SharedTableColor>#00FFFF</SharedTableColor>
</Settings>
Parse Error:
Error Domain=NSXMLParserErrorDomain Code=5 "The operation couldn’t be completed. (NSXMLParserErrorDomain error 5.)"
Refer the answer given by #mobibob here==> What is the meaning of NSXMLParserErrorDomain error 5.?
According to Dave DeLong,
That means it's having issues parsing your file.
I think it may be the XSLT reference in the XML - as it points to the webserver. I will review and get back to this question with an improved answer.
It was the path of the file. My code wasn't even close to the right location -- and I was missing a trailing letter 's'. The error code definition implies a "premature end of file", which caused me to truncate my file without any success. I then went back to basics and iterated on the file system to look for my file.
I debugged by using the NSFileManager to iterate to my file and then verified that it was loadable with the contentsAtPath method. I was able to dump it with NSLog(). Once I was convinced that the file was well-formed and loaded in raw form, I made certain that my NSURL was constructed with the same syntax and methods. Then it loaded correctly. Now I can load either a network file "full-featured" content or a local "sample" content.
NSDirectoryEnumerator *dirEnumerator = [[NSFileManager defaultManager] enumeratorAtPath: NSHomeDirectory()];
NSString *something;
NSString *f;
while( something = [dirEnumerator nextObject] ) {
f = [[[NSString alloc] initWithFormat: #"%#/%#", NSHomeDirectory(), something] autorelease];
if( [f hasSuffix :#"two_cookies.xml"] ){
NSData *nsData = (NSData*) [[NSFileManager defaultManager] contentsAtPath: f];
NSLog(#"%#", nsData );
}
}
Output
2009-10-22 00:47:40.147 MyApp[13843:20b]
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! :)
I'm trying to parse a Stack Overflow RSS feed of a specific question:
https://stackoverflow.com/feeds/question/2110875
For this I'm using the TouchXML library. There seems to be a problem in the following code:
CXMLDocument *parser = [[CXMLDocument alloc] initWithData:sourceData options:0 error:nil];
NSArray *allEntries = [parser nodesForXPath:#"//entry" error:nil];
NSLog(#"Found entries: %d",[allEntries count]); //Returns 0
The NSLog statement should return the count of all entries in the feed. In this case it should be '3', problem is that it returns 0.
I found that this piece of code does work:
CXMLDocument *preParser = [[CXMLDocument alloc] initWithData:sourceData options:0 error:nil];
NSString *sourceStringUTF8 = [preParser XMLString];
[preParser release];
CXMLDocument *parser = [[CXMLDocument alloc] initWithData:[sourceStringUTF8 dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSArray *allEntries = [parser nodesForXPath:#"//entry" error:nil];
NSLog(#"Found entries: %d",[allEntries count]); //Returns 3, which is ok
But using this seems hacky (it probably is) and introduces a few other sporadic bugs.
As far as I know the Xpath expression is correct. I've checked it using this page as well.
Can anyone help me with this problem, or point me in the right direction.
Thanks.
I had a very similar problem. This has something to do with the xml namespace, which TouchXML doesn't support very well (a known issue).
I believe that in your hack, the namespace wasn't passed into the second parser, that's why it works.
A easier way is just to change
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
replaced with simply
<html>
and xPath now works.
Maybe start by actually using that error argument to nodesForXPath:error to see if it returns an error? And check if allEntries is not nil after making that call?
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.
Im using NSXMLParser to dissect a xml package, I'm receiving &apos inside the package text.
I have the following defined for the xmlParser:
[xmlParser setShouldResolveExternalEntities: YES];
The following method is never called
- (void)parser:(NSXMLParser *)parser foundExternalEntityDeclarationWithName:(NSString *)entityName publicID:(NSString *)publicID systemID:(NSString *)systemID
The text in the field before the &apos is not considered by the parser.
Im searching how to solve this, any idea???
Thanks in advance
Alex
XML package portion attached:
<?xml version="1.0" encoding="ISO-8859-1"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="urn:appwsdl"><SOAP-ENV:Body><ns1:getObjects2Response xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"><return xsi:type="tns:objectsResult"><totalRecipes xsi:type="xsd:string">1574</totalObjects><Objects xsi:type="tns:Item"><id xsi:type="xsd:string">4311</id><name xsi:type="xsd:string"> item title 1 </name><procedure xsi:type="xsd:string">item procedure 11......
Here is what I did, after referring a different answer from here.
I replaced all the occurrences of the ' in the xml with "'" when the data is received from NSURLConnection object. Then I give that data to the parser.
So what I do is:
NSData* parserData = [self resolveHTMLEntities: self.receivedData];
NSXMLParser* parser = [[NSXMLaParser alloc] initwithData:parserData];
Here is the resolveHTMLEntitites method:
NSString *xmlCode = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSMutableString *temp = [NSMutableString stringWithString:xmlCode];
// Replace all the entities
[temp replaceOccurrencesOfString:#"'" withString:#"'" options:NSLiteralSearch range:NSMakeRange(0, [temp length])];
NSData *finalData = [temp dataUsingEncoding:NSUTF8StringEncoding];
return finalData;
The catch is that ' gets converted to ' thats why we need to replace that occurrence.
Note: No memory management is performed in the above block of code.
Hope this helps.
The standard entities are <, >, &, and ". ' is an html entity reference. Does your XML refer to the XHTML namespace or some other namespace that has ' defined?
(BTW, would be nice to see a small segment of the XML including the header.)