I want to parse rss that have child with the same name but different value. In this case, i want to parse the value from child name 'category'.
Here's the RSS Format:
<item><title>HAC Algorithm by holiccorp</title>
<link>http://www.freelancer.com/projects/PHP-Javascript/HAC-Algorithm.html</link>
<description>Need someone good at javascript coding and HAC Algorithm. I need someone to create and analyze the code,script and logic. More details will be given after discussion. ASAP project. (Budget: $30-$250 USD, Jobs: Algorithm, HTML, Javascript, PHP, Website Testing)</description>
<pubDate>Sun, 23 Sep 2012 13:20:17 -0400</pubDate>
<guid isPermaLink="false">Freelancer.com_project_2509687</guid>
<category domain="http://www.freelancer.com/jobs/">Algorithm</category>
<category domain="http://www.freelancer.com/jobs/">HTML</category>
<category domain="http://www.freelancer.com/jobs/">Javascript</category>
<category domain="http://www.freelancer.com/jobs/">PHP</category>
<category domain="http://www.freelancer.com/jobs/">Website Testing</category>
<coop:keyword>Algorithm</coop:keyword>
<coop:keyword>HTML</coop:keyword>
<coop:keyword>Javascript</coop:keyword>
<coop:keyword>PHP</coop:keyword>
<coop:keyword>Website Testing</coop:keyword>
<coop:keyword>project 2509687</coop:keyword>
<coop:keyword>HAC Algorithm</coop:keyword>
</item>
I did something like this:
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSLog(#"blogTitle %#",blogTitle);
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSString *articleDescription = [item valueForChild:#"description"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
NSDate *timeStamp = [NSDate date];
NSString *category = [item valueForChild:#"category"];
}
Fron this code, I got only first value from child name category. How do i parse all value from this child and show in one line? Any idea?
Many Thanks
You have to study more about GDataXML attribute parsing methods
The below links may help you
example-code-for-parsing-xml-and-get-attributes
parsing-xml-attribute-using-gdataxmldocument
see the GData example here
Related
I have a very simple xml file by name options.xml
<Dat>
<Name>Tom</Name>
<Option>1</Option>
</Dat>
Using NSXML I am trying to change "Tom" to "Jim" and save the file. How can I do that. I read many document and there is no straight forward solution. Can some one help me with the code ?
update: I ended up in trying with Gdatasxml
-(void)saveToXML
{
NSString* path = [[NSBundle mainBundle] pathForResource:#"options" ofType:#"xml"];
NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:path];
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
GDataXMLElement *rootElement = [GDataXMLElement elementWithName:#"Dat"];
NSArray *mySettings = [doc.rootElement elementsForName:#"Dat"];
for (GDataXMLElement *mySet in mySettings)
{
NSString *name;
NSArray *names = [mySet elementsForName:#"Name"];
if (names.count > 0)
{
GDataXMLElement *childElement = (GDataXMLElement *) [names objectAtIndex:0];
name = childElement.stringValue;
NSLog(childElement.stringValue);
[childElement setStringValue:#"Jim"];
}
}
[xmlData writeToFile:path atomically:YES];
}
But this is not saving the data. Help.
Editing XML is a little difficult in iOS. You need to parse the original xml to a model and then form the xml.
You can make use of 3rd party library such as GDataXML for forming XML from a data source.
//Edited user info saved in a dictionary
NSDictionary *dictionary = #{#"Name": #"Jim", #"Option":#"1"};
GDataXMLElement *rootElement = [GDataXMLElement elementWithName:#"Dat"];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
GDataXMLElement *element = [GDataXMLElement elementWithName:key stringValue:obj];
[rootElement addChild:element];
}];
//xml document is formed
GDataXMLDocument *document = [[GDataXMLDocument alloc]
initWithRootElement:rootElement];
NSData *xmlData = document.XMLData;
NSString *filePath = [self savedXMLPath];
//XML Data is written back to a filePath
[xmlData writeToFile:filePath atomically:YES];
Create a class that is essentially an XML "node". Then in your parser setup a system of these XML nodes in the same fashion as you read them. Then search through that body and find the element that you would like to change. Change it. Then write a function that goes through these "node" objects and writes a new NSString in XML format and save that string to file. There is no real easy way that I know of to write XML files. I'm sure someone has a library out there to do it, but I had very complex XML's to deal with so I wrote my own. If you would like specific code let me know and I can try to give you parts of what you may need.
You Can use GDATAXML for changing XML node
Here is Working Code snippet
NSString *XMLString = #"<Dat><Name>Tom</Name><Option>1</Option></Dat>";
NSError *error = nil;
GDataXMLElement *newElement = [[GDataXMLElement alloc] initWithXMLString: XMLString error: &error];
NSLog(#"New element: %# error: %#", newElement, error);
if(nil == error)
{
GDataXMLElement *childElement = [[newElement elementsForName: #"Name"] objectAtIndex: 0];
[childElement setStringValue:#"Jim"];
childElement = [[newElement elementsForName: #"Option"] objectAtIndex: 0];
[childElement setStringValue:#"2"];
}
NSLog(#"New element now: %#", newElement);
Check by using this code snippet
I am having an issue with a blog I am working on. The method I am using to parse is:
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels)
{
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items)
{
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
}
}
EDIT: XML LOOKS LIKE:
<item>
<title>Your Direction Determines Your Destination</title>
<link>http://treymorgan.podbean.com/2012/06/05/your-direction-determines-your-destination/</link>
<comments>http://treymorgan.podbean.com/2012/06/05/your-direction-determines-your-destination/#comments</comments>
<pubDate>Tue, 05 Jun 2012 17:57:07 +0000</pubDate>
<dc:creator>treymorgan</dc:creator>
<category></category>
<guid isPermaLink="false">http://treymorgan.podbean.com/2012/06/05/your-direction-determines-your-destination/</guid>
<description><![CDATA[Part 1 of the series … Road Trip
]]></description>
<content:encoded><![CDATA[<p>Part 1 of the series … Road Trip
</p>
]]></content:encoded>
<wfw:commentRss>http://treymorgan.podbean.com/2012/06/05/your-direction-determines-your-destination/feed/</wfw:commentRss>
<enclosure url="http://treymorgan.podbean.com/mf/feed/x52488/DirectionDeterminesyourDestination.mp3" length="32015229" type="audio/mpeg"/>
</item>
This way I can get the title of the article from the Title tag within the XML. Most xmls I have parsed have included the mp3, either in the "guid" or "link" tag. However, the current feed I am working with, looks like this:
<enclosure url="http://treymorgan.podbean.com/mf/feed/bf8mvq/Accommoditions.mp3" length="29865594" type="audio/mpeg"/>
How can I pass the url from the enclosure into an NSString?
Something like [[item attributeForName: #"url"] stringValue] should do it. Depending on the actual location of the enclosure element in the XML tree, you might need to use another element instead of channel of course.
Answer is
[[[[item elementsForName: #"enclosure"] lastObject] attributeForName: #"url"] stringValue]
I'm totally new to XML.
Does anyone have a sample code to help me build a custom class that would parse Microsoft .asx files to play mms streams in sequence on the iPhone?
Some Googling revealed to me that .xml and .asx are somewhat related, though the second one is very limited if compared to the first.
I need to play three streams in sequence, inside an .asx container like this:
<asx version="3.0">
<TITLE>MYSONGS</TITLE>
<entry>
<TITLE>www.mysite.com</TITLE>
<ref href="mms://mysite.com/musicFolder/song1.wma" />
</entry>
<entry>
<TITLE>MYSONGS</TITLE>
<ref href="mms://mysite.com/musicFolder/song2.wma" />
</entry>
<entry>
<TITLE>www.mysite.com</TITLE>
<ref href="mms://mysite.com/musicFolder/song3.wma" />
</entry>
</asx>
I'm already able to parse the mms stream, decode and play the wma file. I'm just not able yet to parse .asx content, to play the streams in sequence. Thanks!
In my case I've been able to successfully parse .asx files using TouchXML, using this code (that I modified from the original version available at http://foobarpig.com/iphone/parsing-xml-element-attributes-with-touchxml.html):
// we will put parsed data in an a array
NSMutableArray *res = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString: #"http://www.yoursite.com/WindowsMediaDotCom/theFileToParse.asx"];
/* have TouchXML parse it into a CXMLDocument */
CXMLDocument *document = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];
NSArray *nodes = NULL;
// searching for piglet nodes
nodes = [document nodesForXPath:#"//ref" error:nil];
for (CXMLElement *node in nodes) {
NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
int counter;
for(counter = 0; counter < [node childCount]; counter++) {
// common procedure: dictionary with keys/values from XML node
[item setObject:[[node childAtIndex:counter] stringValue] forKey:[[node childAtIndex:counter] name]];
}
// and here it is - attributeForName! Simple as that.
[item setObject:[[node attributeForName:#"href"] stringValue] forKey:#"href"]; // <------ this magical arrow is pointing to the area of interest
[res addObject:item];
[item release];
}
// and we print our results
NSLog(#"%#", res);
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!
I am doing Fconnect in that when a user connects to facebook I get a string like this
{"id":"100001480456987","name":"Vishnu Gupta","first_name":"Vishnu","last_name":"Gupta","link":"http:\/\/www.facebook.com\/profile.php?id=100001480456987","education":[{"school":{"id":"110885222265513","name":"st.joseph"},"type":"High School"}],"gender":"male","email":"vishu.gupta20#gmail.com","timezone":5.5,"locale":"en_US","verified":true,"updated_time":"2010-11-27T10:10:25+0000"}
Now I want to split the id name and email id of the user so that I can store it in my database.
Can someone tell me how to do it????
You don't want to split a string to get those values. Instead, you want to parse the JSON to grab data. I've used this library, it works very well: http://stig.github.com/json-framework/
Hope this helps!
EDIT: Some sample code:
NSDictionary *dict = [responseFromFacebook JSONValue];
NSString *facebookID = [dict objectForKey:#"id"];
NSString *name = [dict objectForKey:#"name"];
NSString *email = [dict objectForKey:#"email"];
this looks like JSON. Some information on JSON handling with Objective C is available at
http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c
Use a JSON parser. See this answer for links to stackoverflow questions about the different JSON libraries available.
Of course I'd also like to mention my own JSON parsing library, JSONKit. At the time of this writing I think it's fair to say that it's the fastest JSON parser out there.
Try this
NSDictionary *dict=[[NSDictionary alloc]init];
string=[string stringByReplacingOccurrencesOfString:#"{" withString:#""];
string=[string stringByReplacingOccurrencesOfString:#"}" withString:#""];
string=[string stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSArray *seperated=[string componentsSeparatedByString:#","];
for(int index=0;index<[seperated count];index++)
{
NSArray *sub=[[seperated objectAtIndex:index] componentsSeparatedByString:#":"];
[dict setValue:[sub objectAtIndex:0] forKey:[sub objectAtIndex:1]];
}