2
我有一個XML文檔是這樣的:ASP.NET轉換XML字符串字典
<Tags>
<Key>
<Name>Model</Name>
<Value>Raggae</Value>
</Key>
<Key>
<Name>Rate</Name>
<Value>21</Value>
</Key>
</Tags>
我想從它創建一個字典,包含關鍵的名稱元素和價值元素的值。
請幫我。
這是我寫的代碼,我婉知道它是否足夠有效的:
IDictionary<string, string> XmlToDictionary(string data)
{
XElement rootElement = XElement.Parse(data);
var dict = new Dictionary<string, string>();
foreach (var el in rootElement.Elements())
{
if (el.Name.LocalName == "Key")
{
foreach (var sub in el.Elements())
{
string key = null;
string val = null;
if (sub.Name.LocalName == "Name") key = sub.Value;
if (sub.Name.LocalName == "Value") val = sub.Value;
if (key != null && !dict.ContainsKey(key)) dict.Add(key, val);
}
}
}
return dict;
}
http://whathaveyoutried.com?請告訴我們你到目前爲止的情況。 SO不是代碼編寫服務,如果您提供了自己的工作證據,您將得到更好的迴應。請參閱[幫助頁面](http://stackoverflow.com/help)。 – freefaller
對不起,省略代碼 – Arsene