GDataXml Parsing Issues in iPhone - iphone

here this is below the code i need to parse the section and Company Sub data Using GDataXml in iOS.
-<MainList>
<FirstMessage>Right</FirstMessage>
<SecondMessage>Wrong</SecondMessage>
<Status>0</Status>
-<CompanyList>
-<Company>
<Address1>12447 Hedges Run Drive</Address1>
<Address2>#B-1 </Address2>
<City>Lake Ridge</City>
<CompanyName>Starbucks</CompanyName>
<CreatedBy>example#example.com</CreatedBy>
-</Company>
-<Company>
<Address1>12447 Hedges Run Drive</Address1>
<Address2>#B-1 </Address2>
<City>Lake Ridge</City>
<CompanyName>Starbucks</CompanyName>
<CreatedBy>example#example.com</CreatedBy>
-</Company>
</CompanyList>
</MainList>
Here is My Try i am getting every thing fine but i am getting nothing in NSArray arr.
NSArray *channels = [rootElement elementsForName:#"CompanyList"];
for (GDataXMLElement *icon in channels) {
NSArray *arr = [icon elementsForName:#"Company"];
if ([arr count]>0)
{
NSlog(#"Done");
}
}

See this answer, this answer is helpful for u. NSXMLParser example

Hello guys i figured it out as follows
GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc]initWithData:xmlData options:0 error:&error];
NSLog(#"Error:%#",[error description]);
NSArray *getData = [[xmlDocument rootElement]elementsForName:#"CompanyList"];
NSArray *tempArray = [[NSMutableArray alloc]init];
for(GDataXMLElement *e in getData)
{
NSArray *el = [e elementsForName:#"Company"];
for (GDataXMLElement *e in el) {
static int count =0;
NSString *testString = [[[e elementsForName:#"Address1"] objectAtIndex:0] stringValue];
NSLog(#"Company %d : %#",count+1, testString);
}

Related

Extracting Unique Objects from a Data Array

I want to add names in a data array only if the name does not previously exist in the data array. When I attempt to print these names, I do get repetitions. Is there a way to solve this?
-(NSMutableArray *)autoComplete
{
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSString *url = [NSString stringWithFormat:#"%#45.25,-95.25&limit=100&client_id=Von0J4Bu6INiez5bGby2R&client_secret=50sUjSbg7dba8cQgtpdfr5Ns7wyYTqtmKpUU3khQ",kWSURL];
NSDictionary * returnDict = (NSDictionary *) [self callWebService:url];
if([returnDict objectForKey:#"success"])
{
NSArray *responceArray = [returnDict objectForKey:#"response"];
for (NSDictionary *dict in responceArray) {
placeDC *place = [[placeDC alloc]init];
NSDictionary *placeDict = (NSDictionary *)[dict objectForKey:#"place" ];
NSDictionary *loctionDict =(NSDictionary *)[dict objectForKey:#"loc"];
NSString * name =[placeDict objectForKey:#"name"];
NSString * stateFull =[placeDict objectForKey:#"stateFull"];
NSString * countryFull =[placeDict objectForKey:#"countryFull"];
NSString *latitude =[loctionDict objectForKey:#"lat"];
NSString *longitude = [loctionDict objectForKey:#"long"];
place.placeNmae=name;
place.countryFullName=countryFull;
place.stateFullName=stateFull;
NSLog(#"%# ",stateFull);
place.latitude=[latitude doubleValue];
place.longitude=[longitude doubleValue];
[dataArray addObject:place];
}
}
return dataArray;
}
First Check that is there any response from the Server side or not, to check response use NSLog() or Break Points.
if response is ok then put a the following check your code
if (![dataArray containsObject:#"Some Name"])
{
// add Object
}
You could add the name NSString to an NSSet and check in every cycle whether it contains it or not.
Inside your if you could write something like:
NSArray *responceArray = [returnDict objectForKey:#"response"];
NSSet *names = [[NSSet alloc] init];
for (NSDictionary *dict in responceArray) {
NSDictionary *placeDict = (NSDictionary *)[dict objectForKey:#"place" ];
NSString * name =[placeDict objectForKey:#"name"];
if (![names containsObject:name]) {
[names addObject:name];
placeDC *place = [[placeDC alloc]init];
NSDictionary *loctionDict =(NSDictionary *)[dict objectForKey:#"loc"];
NSString * stateFull =[placeDict objectForKey:#"stateFull"];
NSString * countryFull =[placeDict objectForKey:#"countryFull"];
NSString *latitude =[loctionDict objectForKey:#"lat"];
NSString *longitude = [loctionDict objectForKey:#"long"];
place.placeNmae=name;
place.countryFullName=countryFull;
place.stateFullName=stateFull;
NSLog(#"%# ",stateFull);
place.latitude=[latitude doubleValue];
place.longitude=[longitude doubleValue];
[dataArray addObject:place];
}
}
Hope this helps!
Do one thing, add your dict in another array and search in this array that data already exist or not,
[tempAry addObject: dict];
and before insertion
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == %#", name];
NSArray *filteredArray = [tempAry filteredArrayUsingPredicate:predicate];
if ([filteredArray count] == 0)
{
[dataArray addObject:place];
}
else{
//Already exist
}
Why don't you create a separate dictionary, as an ivar or property of you class, for storing our required value, say it as :
NSMutableDictionary *uniqueValueDict=[NSMutableDictionary new];
And keep storing your required value and key as:
[uniqueValueDict setObject:stateFull forKey:uniqueValueDict];
Your work will be done.
This is the easiest solution that i have applied and this should get you going in picking up unique elements out of array.
NSArray * claimedOfferArray = [[NSArray alloc]initWithObjects:#"A",#"B",#"A",#"C",#"B" nil];
NSArray * distinctArray = [[NSArray alloc]init];
distinctArray =[[NSSet setWithArray:claimedOfferArray] allObjects];
This code will also work with NSMutableArray
Let me know if it works for you..:).

iPhone - difference between GDataXMLNode and GDataXMLElement, and how to use them

As the google doc is not available anymore, I'm lost with those concepts.
What is a node, and what is an element (that inherits the node) ?
How can I switch from nodes to elements. I mean, for example, if I write :
NSError* error;
NSData* xmlData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"ForTesting" ofType:#"xml"]];
error = nil;
GDataXMLDocument* XMLDoc = [[[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error] autorelease];
if (XMLDoc == nil) {
NSLog(#"%#", error.description);
return;
}
GDataXMLNode* xmlElement = [[XMLDoc nodesForXPath:#"//root/fileVersion" error:nil] objectAtIndex:0];
NSString* fileVersion = xmlElement.stringValue;
GDataXMLNode* xmlList = [[XMLDoc nodesForXPath:#"//root/list" error:nil] objectAtIndex:0]; // single item
After that code, how can I write something like that to switch to GDataXMLElement instead of continuing with GDataXMLNode, that would requires me to continue using XPath (I don't want to use it past that point) :
// code don't work : elementsForName is not defined for GDataXMLNode
for (GDataXMLElement* xmlObject in [xmlList elementsForName:#"object"]) {
MyClass* obj = [[[MyClass alloc] initWithXMLElement:xmlObject] autorelease];
}
GDataXMLNode is obviously the classes you use for XML parser- GDataXMLNode.h/.m
In the code you have given returns an array. You can use.
NSArray *myArray = [XMLDoc nodesForXPath:#"//root/fileVersion" error:nil];
You can iterate myArray like this.
for (GDataXMLElement *nodeXmlElt in myArray)
{
//some code
}
Each of my nodeXmlElt will be like given below.
<fileVersion>
<title>San Francisco CBS News</title>
<link>http://news.google.com/news/</link>
<fileVersion>
//getting title
NSArray *elementArray = [nodeXmlElt elementsForName:#"title"];
GDataXMLElement *gdataElement = (GDataXMLElement *)[elementArray objectAtIndex:0];
NSString *title = gdataElement.stringValue; //returns 'San Francisco CBS News'

How can I parse this xml using GDataXML parser?

<list>
<OrderData HASH="1408108039"></OrderData>
<OrderData HASH="208524692">
<id>97</id>
<customer>
<CustomerData HASH="2128670187"></CustomerData></customer>
<billingAddress></billingAddress><deliveryAddress></deliveryAddress>
<orderDetail>
<list>
<OrderDetailData HASH="516790072"></OrderDetailData>
<OrderDetailData HASH="11226247"></OrderDetailData>
<OrderDetailData HASH="11226247"></OrderDetailData>
</list>
</orderDetail>
<log/>
</OrderData>
<OrderData HASH="1502226778"></OrderData>
</list>
I cannot find a solution to find the number of OrderDetailData elements? I also read http://iphonebyradix.blogspot.com/2011/03/using-gdata-to-parse-xml-file.html this url.
Thanks in advance.
Edit:
I am explaining my requirement again. In this xml there will be multiple OrderData element. Now I have to count the number of OrderDetailData elemnts from a particular OrderData element. Suppose that, according to my xml, the current parsed xml has one OrderData element, named id and its value is 97. Now, I have to count how many OrderDetailData elements are contained in the OrderData(whichid` is 97).
This is a simple example how to retrieve some data. This example is very simple and not use XPath expression. I suggest you first understand how it works and then use XPath expression. In my opinion it is not useful to use XPath expression if you cannot understand how the parser works.
NSString* path = [[NSBundle mainBundle] pathForResource:#"test2" ofType:#"xml"];
NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:path];
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData
options:0 error:&error];
//NSLog(#"%#", doc.rootElement); // print the whole xml
NSArray *orderDataArray = [doc.rootElement elementsForName:#"OrderData"];
for (GDataXMLElement *orderDataElement in orderDataArray) {
if([orderDataElement childCount] > 0)
{
NSString *attributeForOrderDataElement = [(GDataXMLElement *) [orderDataElement attributeForName:#"HASH"] stringValue];
NSLog(#"attributeForOrderDataElement has value %#", attributeForOrderDataElement);
GDataXMLElement* idElement = (GDataXMLElement*)[[orderDataElement elementsForName:#"id"] objectAtIndex:0];
NSLog(#"id has value %#", idElement.stringValue);
GDataXMLElement* orderDetailElement = (GDataXMLElement*)[[orderDataElement elementsForName:#"orderDetail"] objectAtIndex:0];
GDataXMLElement* listElement = (GDataXMLElement*)[[orderDetailElement elementsForName:#"list"] objectAtIndex:0];
NSArray* orderDetailDataArray = [listElement elementsForName:#"OrderDetailData"];
int count = 0;
for (GDataXMLElement *orderDetailDataElement in orderDetailDataArray) {
NSString *attributeForOrderDetailDataElement = [(GDataXMLElement *) [orderDetailDataElement attributeForName:#"HASH"] stringValue];
NSLog(#"attributeForOrderDetailDataElement has value %#", attributeForOrderDetailDataElement);
count++;
}
NSLog(#"%d", count);
}
}
[doc release];
[xmlData release];
This is the output console:
attributeForOrderDataElement has value 208524692 <-- HASH value
id has value 97 <-- id value
attributeForOrderDetailDataElement has value 516790072 <-- HASH value
attributeForOrderDetailDataElement has value 11226247
attributeForOrderDetailDataElement has value 11226247
3 <-- the count
Hope it helps.
Edit
test2.xml contains your file but you could pass it as a string. You can also pass as parameters as string like the following:
NSString* xmlString = #"<list>"
"<OrderData HASH=\"1408108039\"></OrderData>"
"<OrderData HASH=\"208524692\">"
"<id>97</id>"
"<customer>"
"<CustomerData HASH=\"2128670187\"></CustomerData>"
"</customer>"
"<billingAddress></billingAddress>"
"<deliveryAddress></deliveryAddress>"
"<orderDetail>"
"<list>"
"<OrderDetailData HASH=\"516790072\"></OrderDetailData>"
"<OrderDetailData HASH=\"11226247\"></OrderDetailData>"
"<OrderDetailData HASH=\"11226247\"></OrderDetailData>"
"</list>"
"</orderDetail>"
"<log/>"
"</OrderData>"
"<OrderData HASH=\"1502226778\"></OrderData>"
"</list>";
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithXMLString:xmlString options:0 error:&error];
I found TouchXML easy in parsing and you can directly access data needed from xml
First of all Download TouchXML and add libxml2.dylib framework to your project.
change buildsetting for "Header Search Path" and add "/usr/include/libxml2"
Import TouchXML.h to your file
//Access document
CXMLDocument *parserDoc = [[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:&err];
//Access root element and access children in heirarchy
CXMLElement *root = [parserDoc rootElement];
NSArray *places = [[[root children] objectAtIndex:0] children];
Else
//Access node by node
NSString *location =[[[[[parserDoc nodesForXPath:#"/xml_api_reply/weather/forecast_information/city" error:nil] objectAtIndex:0] attributeForName:#"data"] stringValue] retain];
If the OrderDetailData is present in 2nd object of array all the time, u can use the below
NSArray* arr = [[XMLelement elementForName:#"list"] elementsForName:#"OrderData"];
NSXMLElement* listElement = [[[arr objectAtIndex:1] elementForName:#"orderDetail"] elementForName:#"list"];
NSArray* orderDetailArray* = [listElement elementsForName:#"OrderDetailData"];
In this u can get the OrderDetailData elements in the array, and u can parse the data in loop. to get HASH value use.
NSString* hash = [[orderDetailArray objectAtIndex:0] stringValueForAttribute:#"HASH"];
This is the below code, i have tried. I got the right output.. check out
NSString* xmlString = #"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<list>"
"<OrderData HASH=\"1408108039\"></OrderData>"
"<OrderData HASH=\"208524692\">"
"<id>97</id>"
"<customer>"
"<CustomerData HASH=\"2128670187\"></CustomerData></customer>"
"<billingAddress></billingAddress><deliveryAddress></deliveryAddress>"
"<orderDetail>"
"<list>"
"<OrderDetailData HASH=\"516790072\"></OrderDetailData>"
"<OrderDetailData HASH=\"11226247\"></OrderDetailData>"
"<OrderDetailData HASH=\"11226247\"></OrderDetailData>"
"</list>"
"</orderDetail>"
"<log/></OrderData>"
"<OrderData HASH=\"1502226778\"></OrderData>"
"</list>";
NSXMLDocument* doc = [[NSXMLDocument alloc] initWithData:[xmlString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSXMLElement* rootElement = [doc rootElement];
NSArray* arr = [rootElement elementsForName:#"OrderData"];
NSXMLElement* orderDataElement;
for (int i = 0; i < [arr count]; i++)
{
int Id = 0;
Id = [[arr objectAtIndex:i] integerValueForNode:#"id"];
if (Id != 0)
{
orderDataElement = [arr objectAtIndex:i];
break;
}
}
NSArray* orderDetailArray = [[[orderDataElement elementForName:#"orderDetail"]
elementForName:#"list"]
elementsForName:#"OrderDetailData"];
for (int j = 0; j < [orderDetailArray count]; j++)
{
NSLog(#"%#", [[orderDetailArray objectAtIndex:j] stringValueForAttribute:#"HASH"]);
}

How can i Parse xml data using GDataXML parser in iPhone application development?

-<stat>
<visitor>4</visitor>
<uniqueVisitor>2</uniqueVisitor>
<order>41</order>
<revenue>20658</revenue>
<conversionRate>48</conversionRate>
<newProduct>25</newProduct>
<outOfStockProduct>11</outOfStockProduct>
</stat>
From this xml i want to get the element name "visitor" & "uniqueVisitor" and their corresponding values using GDataXML parser.
Till now i have done these.
xmlFileLocation = [NSURL URLWithString:#"someurl....abc.php"];
NSData *xmlData = [[NSMutableData alloc] initWithContentsOfURL:xmlFileLocation];
xmlDocument = [[GDataXMLDocument alloc]initWithData:xmlData options:0 error:&error];
if (nil == xmlDocument) {
NSLog(#"could not load Branch.xml file");
}
else {
NSLog(#"Loading desire xml url for dashboard");
[self GDataXmlParser];
}
Using a tutorial i have done this till now. But now i want all of these element name and their corresponding values
-(void)GDataXmlParser{
NSArray *getData = [[xmlDocument rootElement]elementsForName:#"stat"];
records = [[NSMutableArray alloc]init];
tempArray = [[NSMutableArray alloc]init];
for(GDataXMLElement *e in getData){
// What i have to do here????
}
}
look at the answer
NSLog(#"%#", xmlDocument.rootElement);
records = [[NSMutableArray alloc] init];
NSLog(#"Enering in the xml file");
NSString *Visitor = [[[xmlDocument.rootElement elementsForName:#"visitor"] objectAtIndex:0] stringValue];
NSLog(#"Visitor : %#",Visitor);
NSString *UVisitor = [[[xmlDocument.rootElement elementsForName:#"uniqueVisitor"] objectAtIndex:0] stringValue];
NSLog(#"Unique Visitor : %#",UVisitor);
for more see the link I am not able to parse xml data using GDataXML
Follow this link for tutorial :http://iphonebyradix.blogspot.com/2011/03/using-gdata-to-parse-xml-file.html
-(void) GDataXmlParser
{
xmlDocument = [[GDataXMLDocument alloc]initWithData:xmlData
options:0
error:nil];
NSArray *temp = [xmlDocument.rootElement elementsForName:#"stat"];
NSMutableArray *records = [[NSMutableArray alloc]init];
for(GDataXMLElement *e in temp)
{
[records addObject:e];
NSString *Visitor = [[[e elementsForName:#"visitor"] objectAtIndex:0] stringValue];
NSLog(#"Visitor : %#",Visitor);
NSString *UVisitor = [[[e elementsForName:#"uniqueVisitor"] objectAtIndex:0] stringValue];
NSLog(#"Unique Visitor : %#",UVisitor);
}
}
Hope it helps you. Happy iCoding.

iPhone parsing url for GET params

I have an string which is got from parsing an xml site.
http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500
I want to have an NSString function that will be able to parse the value of c.
Is there a default function or do i have to write it manually.
You could use Regular expression via RegExKit Lite:
http://regexkit.sourceforge.net/RegexKitLite/
Or you could separate the string into components (which is less nice):
NSString *url=#"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500";
NSArray *comp1 = [url componentsSeparatedByString:#"?"];
NSString *query = [comp1 lastObject];
NSArray *queryElements = [query componentsSeparatedByString:#"&"];
for (NSString *element in queryElements) {
NSArray *keyVal = [element componentsSeparatedByString:#"="];
if (keyVal.count > 0) {
NSString *variableKey = [keyVal objectAtIndex:0];
NSString *value = (keyVal.count == 2) ? [keyVal lastObject] : nil;
}
}
I made a class that does this parsing for you using an NSScanner, as an answer to the same question a few days ago. You might find it useful.
You can easily use it like:
URLParser *parser = [[[URLParser alloc] initWithURLString:#"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500"] autorelease];
NSString *c = [parser valueForVariable:#"c"]; //c=500
Try the following:
NSURL *url = [NSURL URLWithString:#"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500"];
NSMutableString *parameterString = [NSMutableString stringWithFormat:#"{%#;}",[url parameterString]];
[parameterString replaceOccurrencesOfString:#"&" withString:#";"];
// Convert string into Dictionary
NSPropertyListFormat format;
NSString *error;
NSDictionary *paramDict = [NSPropertyListSerialization propertyListFromData:[parameterString dataUsingEncoding:NSUTF8StringEncoding] mutabilityOption: NSPropertyListImmutable format:&format errorDescription:&error];
// Now take the parameter you want
NSString *value = [paramDict valueForKey:#"c"];
Here is the native iOS approach using NSURLComponents and NSURLQueryItem classes:
NSString *theURLString = #"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500";
NSArray<NSURLQueryItem *> *theQueryItemsArray = [NSURLComponents componentsWithString:theURLString].queryItems;
for (NSURLQueryItem *theQueryItem in theQueryItemsArray)
{
NSLog(#"%# %#", theQueryItem.name, theQueryItem.value);
}