2014
Mar
22
要 Parse xml 之前,要先下载别人写好的 XMLParser Library,这里我使用的是「xml parse」,使用方式还算简单,这里我先定义一个 XML String ,然后用 dictionaryForXMLString 将 XML 读进来,范例如下。
xml parse
- #import "xmlReader.h";
- NSString *xmlContent = [NSString stringWithFormat:@"<?xml version="1.0" encoding="UTF-8" ?>"
- "<xml>"
- "<title>IOS Tutorial</title>"
- "<desc>IOS desc</desc>"
- "</xml>"];
- NSDictionary *dics=[[NSDictionary alloc]
- initWithDictionary:[XMLReader dictionaryForXMLString:xmlContent error:nil]
- ];
- NSLog(@"dics is %@",dics);
将 dics 物件输出的结果如下,可以清楚的看到其资料结构。
result
- dics is {
- xml = {
- desc = {
- text = "IOS desc";
- };
- title = {
- text = "IOS Tutorial";
- };
- };
- }
上述的范例,只是直接将 NSDictionary 输出至萤幕,接下来我要取得 titile 的这个 tag 的值。
Example
- NSArray *tableDicsArray=[dics valueForKey:@"xml"];
- NSLog(@"data = %@", [[tableDicsArray valueForKey:@"title"] valueForKey:@"text"]);
- //output: IOS Tutorial
接著来试一下 Array 的处理,假如我的 XML 格式包含多项的 List,我们一样可以用 Array[0], Array[1] 的方式取得资料。
XML Array
- NSString *xmlContent = [NSString stringWithFormat:@"<?xml version="1.0" encoding="UTF-8" ?>"
- "<xml>"
- "<item><title>IOS Tutorial</title>"
- "<desc>IOS desc</desc></item>"
- "<item><title>IOS Tutorial2</title>"
- "<desc>IOS desc2</desc></item>"
- "</xml>"];
- NSDictionary *dics=[[NSDictionary alloc]initWithDictionary:[XMLReader dictionaryForXMLString:xmlContent error:nil]];
- NSArray *tableDicsArray=[[dics valueForKey:@"xml"] valueForKey:@"item"];
- NSLog(@"data = %@", [[tableDicsArray[1] valueForKey:@"title"] valueForKey:@"text"]);
RSS Content Parse
这是一个简单的 RSS 格式,与 Parse 范例。
Example
- NSString *xmlContent = [NSString stringWithFormat:@"<?xml version="1.0" encoding="UTF-8" ?>"
- "<rss version="2.0">"
- "<title>Puritys Program Blog</title>"
- "<channel>"
- "<title>Puritys Program Blog</title>"
- "<link>http://www.puritys.me/rss/blog</link>"
- "<description></description>"
- "<language>zh-tw</language>"
- "<pubDate>Sat, 22 Mar 2014 23:10:03 +0800</pubDate>"
- "<copyright>www.ewebsite.com.tw</copyright>"
- "<generator>Puritys</generator>"
- "<item>"
- "<title>Javascript Hoisting 与 Closure</title>"
- "<link>http://www.puritys.me/docs-blog/article-242</link>"
- "<description>content</description>"
- "<pubDate>Sat, 22 Mar 2014 00:23:18 +0800</pubDate>"
- "<guid></guid>"
- "</item>"
- "<item>"
- "<title>PHP 判断是否为 Command Line 的方式</title>"
- "<link>http://www.puritys.me/docs-blog/article-241</link>"
- "<description>content</description>"
- "<pubDate>Sat, 22 Mar 2014 00:23:18 +0800</pubDate>"
- "<guid></guid>"
- "</item>"
- "</channel>"
- "</rss>"];
- NSDictionary *dics=[[NSDictionary alloc]initWithDictionary:[XMLReader dictionaryForXMLString:xmlContent error:nil]];
- NSArray *tableDicsArray=[[[dics valueForKey:@"rss"] valueForKey:@"channel"] valueForKey:@"item"];
回應 (Leave a comment)