如何使用linq获取单节点数据

我有以下xml文件

  1 Computer Information tech. True   2 Cate1 MMukh True   

我需要通过id值指定一个类别数据并将它们存储在文本框中。 请你帮助我好吗。 谢谢。

你可以使用LINQ to XML之类的

 XDocument xDoc = XDocument.Load("test.XML"); var item = xDoc.Descendants("category") .FirstOrDefault(r => r.Element("id").Value == "1"); if(item == null) return; string Name = item.Element("name").Value; string Decription = item.Element("description").Value; string active = item.Element("active").Value; 

您可以根据需要将结果分配给TextBoxes。

如何使用Linq To Xml并将元素转换为Dictionary

 var xDoc = XDocument.Parse(xml); int id=1; var dict = xDoc.XPathSelectElement("//category[id=" + id + "]") .Elements() .ToDictionary(e=>e.Name.LocalName , e=>(string)e); Console.WriteLine(dict["description"]); 

只需在对象中反序列化给定的XML并将LINQ应用于对象。 MSDN

 var xml = XDocument.Parse(xmlDataString); var categoryElement = xml.Root .Elements("category") .FirstOrDefault(e => (string)e.Element("id") == "1"); 

首先使用XDocument加载它

 XDocument test = XDocument.Load("test.xml"); 

然后,

  var qry = (from item in test.Descendants("category") where item.Element("id").Value == 1 select new { Name = (string)test.Element("name").Value Description = (string)test.Element("description").Value Active = (string)test.Element("active").Value }).FirstOrDefault(); 

这创建了一个匿名类型,您现在可以像这样显示您的数据:

 if (qry != null) { Console.WriteLine(qry.Name); Console.WriteLine(qry.Description); Console.WriteLine(qry.Active); }