【问题标题】:How can I get single node data using linq如何使用 linq 获取单节点数据
【发布时间】:2013-04-30 04:13:12
【问题描述】:

我有以下 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 值指定的类别数据并将它们存储在文本框中。 请你帮助我好吗。 谢谢。

【问题讨论】:

    标签: c# asp.net xml linq


    【解决方案1】:

    你可以用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;
    

    您可以根据您的要求将结果分配给您的文本框。

    【讨论】:

    • 非常感谢您的热心帮助。
    【解决方案2】:

    如何使用 Linq To Xml 并将元素转换为 Dictionary&lt;string,string&gt;

    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"]);
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:
        var xml = XDocument.Parse(xmlDataString);
        
        var categoryElement = xml.Root
            .Elements("category")
            .FirstOrDefault(e => (string)e.Element("id") == "1");
        

        【讨论】:

          【解决方案5】:

          先用 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);
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-12-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-04-11
            相关资源
            最近更新 更多