在C#中使用LINQ查询XML文件 [英] Query XML file with LINQ in C#
问题描述
我对我的XML文件有一个LINQ查询,看起来像这样
i have a LINQ query for my XML file and it looks like this
IEnumerable<XElement> c = from cli in xEl.Elements(ns + "client")
where cli.Element(ns+"ID").Value == (((Client)cComboBox.SelectedItem).Id +"")
select cli;
它工作正常. 接下来,我要对数据进行迭代,所以我要进行此操作
it works fine.. Next i want to iterate that data so i do this
foreach (XElement el in c)
{
}
我的xml文件如下所示
my xml file looks like this
<client>
<ID>1</ID>
<name>Andrej</name>
通过该迭代,我想提取客户端值(id-> 1 ,名称-> Andrej )
through that iteration, i want to extract clients values (id -> 1, name -> Andrej)
我的猜测是将el.Element("name").Value
放入循环的中间,但这是行不通的...
哦,顺便说一句:我正在用C#进行此操作.
my guess was to put el.Element("name").Value
in the middle of the loop, but that doesn't work...
oh and btw: i'm doing this in C#..
我该怎么办?
btw2:如您所见,我是linq的新手,所以我认为我离这件事还远...
btw2: as you can see i'm new to linq so i think i'm way off track with this one...
任何帮助都会得到帮助!! TNX!
Any help would be appriciated!! TNX!
推荐答案
如果我使用此代码:
public void Run()
{
string fileToLoad = this.GetType().Name + ".xml";
XElement root = XElement.Load(fileToLoad);
var selected = from cli in root.Elements("client")
where cli.Element("ID").Value == "1"
select cli;
System.Console.WriteLine("Selected:");
foreach (var d in selected)
Console.WriteLine("{0}", d.ToString());
System.Console.WriteLine("\nitems:");
foreach (var d in selected)
{
Console.WriteLine("id: {0}", d.Element("ID"));
}
}
此源数据:
<root>
<client>
<ID>1</ID>
<name>Andrej</name>
</client>
<client>
<ID>2</ID>
<name>William</name>
</client>
<client>
<ID>3</ID>
<name>Kate</name>
</client>
</root>
然后...我得到这个结果:
Then... I get this result:
Selected:
<client>
<ID>1</ID>
<name>Andrej</name>
</client>
items:
id: <ID>1</ID>
这篇关于在C#中使用LINQ查询XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!