您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

用 iphone-plist-net 在 C# 中讀寫 plist 檔

編輯:iOS 開發綜合

先前貼過一段手寫 XML 產生 plist 的 C# 程式,但若要讀取既有的 plist,自己解析就辛苦了。網路上找到 iphone-plist-net 這個類別庫,試用之後發現相當順手,這裡記錄一下用法。

寫入 plist

它用型別化的容器包裝資料:PListDict 對應字典、PListArray 對應陣列,再用 PListString/PListInteger 這類包裝型別裝實際值。

// 寫入
var dic = new PListDict();
dic["name"]    = new PListString("WangQiuyun");
dic["age"]     = new PListInteger(25);
dic["address"] = new PListString("北京海淀區永泰莊");

var arr = new PListArray();
arr.Add(new PListInteger(1));
arr.Add(new PListInteger(2));
arr.Add(new PListInteger(3));
arr.Add(new PListInteger(4));
arr.Add(new PListInteger(5));
dic["array"] = arr;

var myRoot = new PListRoot();
myRoot.Root = dic;
myRoot.Save("mytest.plist",  PListFormat.Xml);
myRoot.Save("mytest.bplist", PListFormat.Binary);

同一份資料可以同時輸出成 XML 與 Binary 兩種格式,只要換掉 PListFormat 參數即可。

讀取 plist

PListRoot root = PListRoot.Load(@"mytest.plist");
PListDict dic = (PListDict)root.Root;

PListString name = (PListString)dic["name"];
listBox1.Items.Add(name.Value + " 類型:" + name.Tag);

PListInteger age = (PListInteger)dic["age"];
listBox1.Items.Add(age.Value + " 類型:" + age.Tag);

PListString address = (PListString)dic["address"];
listBox1.Items.Add(address.Value + " 類型:" + address.Tag);

PListArray arr = (PListArray)dic["array"];
listBox1.Items.Add(((PListInteger)arr[0]).Value);
listBox1.Items.Add(((PListInteger)arr[1]).Value);
listBox1.Items.Add(((PListInteger)arr[2]).Value);
listBox1.Items.Add(((PListInteger)arr[3]).Value);
listBox1.Items.Add(((PListInteger)arr[4]).Value);

每個包裝物件都有 Value 與 Tag,後者用來表示實際型別,除錯時很方便。

讀進記憶體再另存

PListRoot root = PListRoot.Load("mytest.plist");
using (MemoryStream memStream = new MemoryStream())
{
    root.Save(memStream, PListFormat.Xml);
    textBox1.Text = Encoding.UTF8.GetString(memStream.ToArray());
}
root.Save("com.apple.springboard.XML.plist", PListFormat.Xml);
root.Save("com.apple.springboard.BIN.plist", PListFormat.Binary);

把 Save 導向 MemoryStream,就能在不落地成檔案的情況下取得 plist 內容,適合在 UI 上預覽或做格式轉換。

使用提醒

這個庫最大的好處是把 plist 的型別系統完整映射到 C#,不必自己處理 <integer>、<true/> 這些標籤。代價是取值時需要明確轉型,型別對不上會直接拋例外,所以讀取未知結構的 plist 時,建議先用 Tag 判斷型別再轉,並把整段包在 try-catch 裡。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved