Parse multi attribute values in iOS - iphone

I am developing an application and
i want to parse the xml but when
it comes in the way of multiple attribute
then how will u do it using the nsxmlparser
<?xml version="1.0" encoding='utf-8' ?>
<Responses Id='7465'>
<Response RequestID="101" FunctionStatus="0" Message="OK"/>
<Result>
<PrimaryID>
<Item ID="1" Text="Aadhar Card"/>
<Item ID="2" Text="Voters ID"/>
<Item ID="3" Text="Driving Licence"/>
<Item ID="4" Text="PAN Card"/>
<Item ID="5" Text="Passport"/>
</PrimaryID>
<Sex>
<Item ID="1" Text="Male"/>
<Item ID="2" Text="Female"/>
</Sex>
<Title>
<Item ID="1" Text="Mr"/>
<Item ID="2" Text="Ms"/>
<Item ID="3" Text="Mrs"/>
</Title>
</Result>
</Responses>

With XMLReader you can get it in a dictionary like this :
file.xml in your resource bundle :
- (void)dataFromXML
{
// Error
NSError *error = nil;
// Request
NSMutableDictionary *xmlDic = nil;
NSData *xmlData = nil;
// Get XML
xmlData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"file" ofType:#"xml"]];
// Parse the XML Data into a NSDictionary
xmlDic = [NSMutableDictionary dictionaryWithDictionary:[XMLReader dictionaryForXMLData:xmlData error:&error]];
// Configure Dictionary
xmlDic = [[[xmlDic objectForKey:#"Responses"] objectForKey:#"Response"] objectForKey:#"Result"];
NSLog(#"%#", xmlDic);
}
file.xml on the web :
- (void)dataWSFromXML
{
// Error
NSError *error = nil;
// Request
NSURLRequest *request = nil;
NSURLResponse *response = nil;
NSMutableDictionary *xmlDic = nil;
NSData *xmlData = nil;
// Get XML
request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://yourXMLfile.xml"]];
xmlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; // You can improve this request
// Parse the XML Data into a NSDictionary
xmlDic = [NSMutableDictionary dictionaryWithDictionary:[XMLReader dictionaryForXMLData:xmlData error:&error]];
// Configure Dictionary
xmlDic = [[[xmlDic objectForKey:#"Responses"] objectForKey:#"Response"] objectForKey:#"Result"];
NSLog(#"%#", xmlDic);
}
But I change your XML like this :
<?xml version="1.0" encoding="UTF-8"?>
<Responses Id='7465'>
<Response RequestID="101" FunctionStatus="0" Message="OK">
<Result>
<PrimaryID>
<Item ID="1" Text="Aadhar Card"/>
<Item ID="2" Text="Voters ID"/>
<Item ID="3" Text="Driving Licence"/>
<Item ID="4" Text="PAN Card"/>
<Item ID="5" Text="Passport"/>
</PrimaryID>
<Sex>
<Item ID="1" Text="Male"/>
<Item ID="2" Text="Female"/>
</Sex>
<Title>
<Item ID="1" Text="Mr"/>
<Item ID="2" Text="Ms"/>
<Item ID="3" Text="Mrs"/>
</Title>
</Result>
</Response>
</Responses>

Related

GDataXMLDocument nodesForXPath return an error

I need your help, i want to parse an XML file using GDataXMLDocument and i want to fetch particular tag's all attributes but when i am using or just provide me the XPath's value to get columnHeading value
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[NSData dataWithContentsOfFile:path] encoding:NSUTF8StringEncoding error:NULL];
NSArray *tempArray = [doc nodesForXPath:#"//root/xsd:schema" namespaces:nil error:nil];
it returns below error.
XPath error : Undefined namespace prefix
xmlXPathEval: evaluation failed
And here is my XML content.
<?xml version="1.0" encoding="utf-8"?>
<SH xmlns="urn:schemas-microsoft-com:xml-analysis:rowset">
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:saw-sql="urn:saw-sql" targetNamespace="urn:schemas-microsoft-com:xml-analysis:rowset">
<xsd:complexType name="R">
<xsd:sequence>
<xsd:element name="S0" saw-sql:columnHeading="SID" saw-sql:columnID="0"/>
<xsd:element name="S1" saw-sql:columnHeading="SNAME" saw-sql:columnID="1"/>
<xsd:element name="S2" saw-sql:columnHeading="CLASS" saw-sql:columnID="2"/>
<xsd:element name="S3" saw-sql:columnHeading="ADD" saw-sql:columnID="3"/>
<xsd:element name="S4" saw-sql:columnHeading="CITY" saw-sql:columnID="4"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
Stuck here from last 3 days. need your help.
Thanks in advance.
Finally i got the solution related to my question... and here is the answer for that.
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[NSData dataWithContentsOfFile:path] encoding:NSUTF8StringEncoding error:NULL];
NSDictionary *myNS = [NSDictionary dictionaryWithObjectsAndKeys:
#"urn:schemas-microsoft-com:xml-analysis:rowset", #"xmlns",
#"http://www.w3.org/2001/XMLSchema", #"xsd",
#"urn:saw-sql",#"saw-sql", nil];
NSArray *tempArray = [doc nodesForXPath:#"//xmlns:RS/xsd:schema/xsd:complexType/xsd:sequence/xsd:element" namespaces:myNS error:nil];
NSMutableArray *keyArray = [[NSMutableArray alloc]initWithCapacity:0];
for(GDataXMLElement *columns in tempArray)
{
GDataXMLNode *xmlElement = [columns attributeForName:#"saw-sql:columnHeading"];
// GDataXMLNode* xmlElement = [[[element2 elementsForName:#"xsd:element"]objectAtIndex:0]attributeForName:#"saw-sql:columnHeading"];
[keyArray addObject:xmlElement.stringValue];
// NSLog(#"%#",xmlElement.stringValue);
}

AFNetworking Form Request (Multiple File uploads in One Request)

We are developing an iOS application. The app is providing single as well as multiple file upload options in one single request. I'm using AFNetworking for single file uploads and which works fine. Now, we need to support multiple file upload. I have got the html code with me which actually does the multiple file uploads from the web.I need to do the same from iOS app. Can anybody suggest how do we do the same using AFNetworking?
<form method="post" action="upload.php?key=ac2a04cc7b6d4420fa5e5eb1701fb0cc1acf7916&channelid=1" enctype="multipart/form-data">
<label>Title:</label> <input name="title" value="My Video Title" /><br />
<label>Date:</label> <input name="date" value="<?php echo time(); ?>" /><br />
<label>Location:</label> <input name="location" value="Sydney, Australia" /><br />
<textarea name="description">The description of the photo/video goes here</textarea><br />
<input name="file[]" type="file" multiple="multiple" /><br />
Use below code to send multiple file to your form. Customize as per your need if required to change anything.
NSArray *imageArray = [NSArray arrayWithObjects:[UIImage imageNamed:#"close_button.png"],[UIImage imageNamed:#"done_button.png"], nil];
__block int i=1;
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:#"yoururl"];
NSMutableURLRequest *request=nil;
request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"yoururl" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
{
for(UIImage *eachImage in imageArray)
{
NSData *imageData = UIImagePNGRepresentation(eachImage);
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:#"file%d",i] fileName:[NSString stringWithFormat:#"abc%d.png",i] mimeType:#"image/png"];
i++;
}
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSData *data = (NSData *)responseObject;
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response -> %#",str);
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error -> %#",[error localizedDescription]);
}];
On server side I have checked with test.php code, I have just printed print_r($_FILES) and it prints following in my case sorry to keep you guessing.
Response -> Array
(
[file1] => Array
(
[name] => abc1.png
[type] => image/png
[tmp_name] => /tmp/phpiWbxSn
[error] => 0
[size] => 1997
)
[file2] => Array
(
[name] => abc2.png
[type] => image/png
[tmp_name] => /tmp/phpwtWTE8
[error] => 0
[size] => 1847
)
)
Hope this helps.
I tried the AFHTTPNetwrok solution,but wasn't working, then i added square brackets in "name" key as below and finally images are uploaded successfully. What might me by problem ?
NSData *imageData = UIImageJPEGRepresentation(img,1);
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:#"images[%d]",i] fileName:[NSString stringWithFormat:#"images%d.jpg",i] mimeType:#"image/jpeg"];

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!

How to parse HTML with TouchXML or some other alternative

I'm trying to parse the HTML presented below with TouchXML but it keeps crashing when I try to extract certain attributes. I'm totally new to the parser world so I apologize for being a complete idiot. I need help to parse this HTML. What I'm trying to accomplish is to parse each attribute and value or what not and copy them to a string. I've been trying to find a good parser to parse HTML and I believe TouchXML is the best I've seen because of Tidy. Speaking of Tidy, How could I run this HTML through Tidy first then parse it? I'm not sure how to do this. Here is the code that I have so far that doesn't work due to it's not pulling everything I need from the HTML. Any help or advice would be much appreciated. Thanks
My current code:
NSMutableArray *res = [[NSMutableArray alloc] init];
// using local resource file
NSString *XMLPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"example.html"];
NSData *XMLData = [NSData dataWithContentsOfFile:XMLPath];
CXMLDocument *doc = [[[CXMLDocument alloc] initWithData:XMLData options:0 error:nil] autorelease];
NSArray *nodes = NULL;
nodes = [doc nodesForXPath:#"//div" error:nil];
for (CXMLElement *node in nodes) {
NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
[item setObject:[[node attributeForName:#"id"] stringValue] forKey:#"id"];
[res addObject:item];
[item release];
}
NSLog(#"%#", res);
[res release];
HTML file that needs to be parsed:
<html>
<head>
<base target="_blank" />
</head>
<body style="margin:2;">
<div id="group">
<div id="groupURL">Group URL</div>
<img id="grouplogo" src="http://images.example.com/groups/image.png" />
<div id="groupcomputer">Group title this would be here</div>
<div id="groupinfos">
<div id="groupinfo-l">Person</div><div id="groupinfo-r">Ralph</div>
<div id="groupinfo-l">Years</div><div id="groupinfo-r">4 years</div>
<div id="groupinfo-l">Salary</div><div id="groupinfo-r">100K</div>
<div id="groupinfo-l">Other</div><div id="groupoth" style="width:15px">other info</div>
</body>
</html>
EDIT: I could use Element Parser but I need to know how to extract the Person's Name from the following example which would be Ralph in this case.
<div id="groupinfo-l">Person</div><div id="groupinfo-r">Ralph</div>
I don't know if you are doing something wrong, but I recommend you to use element parser, the best parser for XML and HTML i've found. Hope this helps.

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

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.