我正在尝试从XML文件读取并将信息保存到字典中。
这就是我的XML的样子:
<?xml version="1.0" encoding="utf-8" ?>
<testUI_root>
<!--Information for the first coded UI Test-->
<codedUITest name ="CodedUITestMethod1">
<description name ="Entering username from CSV" key = "1"/>
<description name ="Entering password from CSV" key = "2"/>
<description name ="Clicking exit" key ="3"/>
</codedUITest>
</testUI_root>
因此,我尝试阅读并保存到字典中,这是我尝试过的方式:
//Load xml
//StringBuilder description = new StringBuilder();
int key;
Dictionary<int, string> valDic = new Dictionary<int, string>();
XDocument xdoc = XDocument.Load("XMLFile1.xml");
//Run query
var lv1s = from lv1 in xdoc.Descendants("codedUITest")
where lv1.Attribute("name").Value.Contains("CodedUITestMethod1")
select new
{
key = lv1.Descendants("key"),
value = lv1.Descendants("name")
};
//loop
foreach (var lv1 in lv1s)
{
foreach (var lv2_k in lv1.key)
{
//it's not entering into this loop
foreach (var lv2_v in lv1.value)
{
// isn't entering here either
key = Convert.ToInt32(lv2_k.Attribute("key").ToString());
valDic.Add(key, lv2_v.Attribute("name").ToString());
}
}
}
foreach (KeyValuePair<int, string> abc in valDic)
{
MessageBox.Show("Value: " + abc.ToString());
}
没有语法错误,这是合乎逻辑的。这就是我的字典的外观。
/*
1.Entering Username from CSV
2.Entering password from CSV
3.Clicking exit
*/
将xml保存到输出目录。(来自vs)尝试过LinqPad中的代码,“查询成功”,但没有输出。我对Linq几乎没有任何经验,如果这个问题/错误很简单,我先向您道歉。谢谢
您在寻找ToDictionary
方法
xdoc.Descendants("codedUITest")
.Where(x => x.Attribute("name").Value.Contains("CodedUITestMethod1"))
.Elements("description")
.ToDictionary(x => (int)x.Attribute("key"), x => (string)x.Attribute("name"));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句