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"];