我有一个类似于这样的xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<resource key="123">foo</resource>
<resource key="456">bar</resource>
<resource key="789">bar</resource>
</data>
Run Code Online (Sandbox Code Playgroud)
我想把它放入一个字典(排序)作为键值对.即:123:foo,456:bar ...等
钥匙是未知的.
我怎样才能做到这一点?
这看起来像Linq到Xml的工作
static void Main(string[] args)
{
XDocument yourDoc = XDocument.Load("the.xml");
var q = from c in yourDoc.Descendants("resource")
orderby (int) c.Attribute("key")
select c.Attribute("key").Value + ":" + c.Value;
foreach (string s in q)
Console.WriteLine(s);
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
如果不使用Linq并且只使用以下内容,这实际上更容易XmlDocument:
SortedDictionary<string, string> myDict = new SortedDictionary<string, string>();
foreach (XmlElement e in myXmlDocument.SelectNodes("/data/resource"))
{
myDict.Add(e.GetAttribute("key"), e.Value);
}
Run Code Online (Sandbox Code Playgroud)
试试这个,
string s = "<data><resource key=\"123\">foo</resource><resource key=\"456\">bar</resource><resource key=\"789\">bar</resource></data>";
XmlDocument xml = new XmlDocument();
xml.LoadXml(s);
XmlNodeList resources = xml.SelectNodes("data/resource");
SortedDictionary<string,string> dictionary = new SortedDictionary<string,string>();
foreach (XmlNode node in resources){
dictionary.Add(node.Attributes["key"].Value, node.InnerText);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10150 次 |
| 最近记录: |