How to read file.xml from resources to NSString with format? - iphone

Actually I have such a code:
NSString *path = [[NSBundle mainBundle] pathForResource: #"connect" ofType: #"xml"];
NSError *error = nil;
NSString *data = [NSString stringWithContentsOfFile: path
encoding: NSUTF8StringEncoding
error: &error];
NSString *message = [NSString stringWithFormat:data, KEY, COUNTRY_ID];
which reads the connect.xml from resources. But on the formating the string (message) APP quits without displaying any errors. How can I read connect.xml from resources to NSString with format?
connect.xml looks like this:
<?xml version="1.0" encoding="utf-16"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:WebApi" 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/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:doQuerySysStatus>
<sysvar xsi:type="xsd:int">1</sysvar>
<country-id xsi:type="xsd:int">%d</country-id>
<webapi-key xsi:type="xsd:string">%#</webapi-key>
</ns1:doQuerySysStatus>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
And defines:
#define KEY #"f7ff34df7a"
#define COUNTRY_ID 228

I think on the last line of code, the KEY and COUNTRY_ID variables are backwards.
In the data, COUNTRY_ID is first.

Maybe you could try using JSON over XML, it is a much easier format to use.

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]);
}

Parsing XML on iPhone with GDataXML

Ugh, I'm having a dickens of a time parsing xml from Exchange Web Services. I want to get the ItemID Id=xyz attribute (AAATAG...). Here is the XML:
<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:Header><t:ServerVersionInfo xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" MajorVersion="8" MinorVersion="3" MajorBuildNumber="137" MinorBuildNumber="0"/></soap:Header><soap:Body><m:FindItemResponse xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"><m:ResponseMessages><m:FindItemResponseMessage ResponseClass="Success"><m:ResponseCode>NoError</m:ResponseCode><m:RootFolder TotalItemsInView="1" IncludesLastItemInRange="true"><t:Items><t:CalendarItem><t:ItemId Id="AAATAGNvb3Blcm1qQG11b2hpby5lZHUARgAAAAAA+Q4xQgA/2kCus7bZbZddngcA8vxBsULRa0S+uFR566ChHwAAAB4BwgAABgoCL+IgvEaj+O0Bl9BG2AAQEOyJMwAA" ChangeKey="DwAAABYAAAAGCgIv4iC8RqP47QGX0EbYABARELYs"/><t:Organizer><t:Mailbox><t:Name>Cooper, Micah</t:Name></t:Mailbox></t:Organizer></t:CalendarItem></t:Items></m:RootFolder></m:FindItemResponseMessage></m:ResponseMessages></m:FindItemResponse></soap:Body></soap:Envelope>
I'm using GDataXML, and here is my code:
- (void)parseFeed:(GDataXMLElement *)doc entries:(NSMutableArray *)entries {
NSLog(#"%#", doc);
NSDictionary *namespaceMappings = [NSDictionary dictionaryWithObjectsAndKeys:#"http://schemas.microsoft.com/exchange/services/2006/messages", #"messages",
#"http://schemas.microsoft.com/exchange/services/2006/types",#"types", nil];
NSArray *items = [doc nodesForXPath:#"//types:CalendarItem" namespaces:namespaceMappings error:nil];
for (GDataXMLElement *item in items) {
NSLog(#"Item: %#", item.stringValue);
NSString *itemID = [[item attributeForName:#"ItemId Id"] stringValue];
NSLog(#"itemID: %#", itemID);
}
}
I'm not pulling the item id -- in fact, it looks as if it is parsing at random places in the XML. Can anyone point me in the right direction? Thanks!

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!

TouchXML - CXMLDocument object failed to initialize

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.

nsxmlparser not solving &apos;

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 &apos; 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:#"&apos;" withString:#"'" options:NSLiteralSearch range:NSMakeRange(0, [temp length])];
NSData *finalData = [temp dataUsingEncoding:NSUTF8StringEncoding];
return finalData;
The catch is that &apos; gets converted to &apos; 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 ". &apos; is an html entity reference. Does your XML refer to the XHTML namespace or some other namespace that has &apos; defined?
(BTW, would be nice to see a small segment of the XML including the header.)