簡體   English   中英

如何使用linq獲取單節點數據

[英]How can I get single node data using linq

我有以下xml文件

<categories>
  <category>
    <id>1</id>
    <name>Computer</name>
    <description>Information tech.</description>
    <active>True</active>
  </category>
  <category>
    <id>2</id>
    <name>Cate1</name>
    <description>MMukh</description>
    <active>True</active>
  </category>
</categories>

我需要獲取一個由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;

您可以根據需要將結果分配給TextBox。

如何使用Linq To Xml並將元素轉換為Dictionary<string,string>

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

首先使用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);
}
var xml = XDocument.Parse(xmlDataString);

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM