パート1:それを解析しながら、WPは現在、とてもダイナミックなタイプのために非常に良いサポートを持っていないあなたは
を求めここで私が解析しようとしているplistファイルの例です。困難ではないでしょう、消費すると醜いでしょう。
このクラスは、XMLにLINQを使用し、PLISTを解析します:
public class PropertyListParser
{
public IDictionary<String, Object> Parse(string plistXml)
{
return Parse(XDocument.Parse(plistXml));
}
public IDictionary<String, Object> Parse(XDocument document)
{
return ParseDictionary(document.Root.Elements("plist")
.Elements("dict")
.First());
}
private IDictionary<String, Object> ParseDictionary(XElement dictElement)
{
return dictElement
.Elements("key")
.ToDictionary(
el => el.Value,
el => ParseValue(el.ElementsAfterSelf("*").FirstOrDefault())
);
}
private object ParseValue(XElement element)
{
if (element == null)
{
return null;
}
string valueType = element.Name.LocalName;
switch (valueType)
{
case "string":
return element.Value;
case "dict":
return ParseDictionary(element);
case "true":
return true;
case "false":
return false;
default:
throw new NotSupportedException("Plist element not supported: " + valueType);
}
}
}
はここに(あなたの例に基づいて)それを使用する方法の例です:
var parsedPlist = new PlistParser().Parse(Plist);
var section0 = (IDictionary<string, object>)parsedPlist["section0"];
var key0 = (IDictionary<string, object>)parsedPlist["key0"];
string type = (string)key0["type"];
bool filter = (bool)key0["filter"];
パート2:あなたは何おそらく必要です
実際にこの方法でそれを消費するコードを書くことはかなり醜いと言われています。あなたのスキーマに基づいて、私は次のことが実際にあなたのアプリケーションに必要なものだと言いたいと思います。
今、あなたは
ConfigEntryLoader
を使用するとき、あなたは辞書の周りに渡すことを維持するために、あなたのコードがはるかに容易になりますConfigEntryオブジェクトのリストを取得
// I'm not sure what your domain object is, so please rename this
public class ConfigEntry
{
public string Name { get; set; }
public string Type { get; set; }
public bool Filter { get; set; }
}
public class ConfigEntryLoader
{
private PropertyListParser plistParser;
public ConfigEntryLoader()
{
plistParser = new PropertyListParser();
}
public ICollection<ConfigEntry> LoadEntriesFromPlist(string plistXml)
{
var parsedPlist = plistParser.Parse(plistXml);
var section0 = (IDictionary<string, object>)parsedPlist["section0"];
return section0.Values
.Cast<IDictionary<string,object>>()
.Select(CreateEntry)
.ToList();
}
private ConfigEntry CreateEntry(IDictionary<string, object> entryDict)
{
// Accessing missing keys in a dictionary throws an exception,
// so if they are optional you should check if they exist using ContainsKey
return new ConfigEntry
{
Name = (string)entryDict["name"],
Type = (string)entryDict["type"],
Filter = (bool)entryDict["filter"]
};
}
}
。
ICollection<ConfigEntry> configEntries = new ConfigEntryLoader()
.LoadEntriesFromPlist(plistXml);
セクションまたはネストされた名前/値のペアのみが必要ですか? –