【问题标题】:LINQ search for a given string value within a nodeLINQ 在节点内搜索给定的字符串值
【发布时间】:2011-07-29 08:03:51
【问题描述】:

我是使用 LINQ 的新手。我想使用 LINQ 检索给定字符串的某个值。我有一个包含以下格式的 XML 文档(files.xml)。

<?xml version="1.0" encoding="utf-8" ?>
<DocumentMappings>
    <DocumtentCategory>
      <CategoryId>001</CategoryId>
      <CategoryName>Checksheet and Lists</CategoryName>
      <DestinationDocumentLibrary>CheckList and Lists</DestinationDocumentLibrary>
      <Multiple>false</Multiple>
    </DocumtentCategory>

    <DocumtentCategory>
      <CategoryId>011</CategoryId>
      <CategoryName>Product Information</CategoryName>
      <DestinationDocumentLibrary>Product Information</DestinationDocumentLibrary>
      <Multiple>true</Multiple>     
    </DocumtentCategory>

</DocumentMappings>

问题

如何使用 LINQ 检索“DestinationDocumentLibrary”的值作为“Checksheet and Lists”的“CategoryName”的字符串。

在上面的示例中,“检查表和列表”作为参数(字符串)传递,并将动态传递给 LINQ 查询。

希望问题很清楚,并在此先感谢您。

【问题讨论】:

  • 所有 3 个都可以正常工作.. 但选择 @Tim 的原因是我在下面的评论中提到的。

标签: c# xml linq linq-to-xml xelement


【解决方案1】:

试试这个:

public string GetDestination(string categoryName, XDocument xDoc)
{

     var query = (from x in xDoc.Descendants("DocumetentCategory")
                  where ((string)x.Element("CategoryName")).Contains(categoryName)
                  select (string)x.Element("DestinationDocumentLibrary")).SingleOrDefault();

     return (string)query;
}

xDoc 是一个包含您的 xml 的 XDocument。

【讨论】:

  • 以上所有 3 个答案都有效,非常感谢你们三个抽出时间来回答。我将@Tim 的答案标记为答案,因为它似乎更适合我所追求的。但是,仅供参考,以上所有 3 个都可以完美地工作..
【解决方案2】:

这可能不是最好的,但它似乎工作:

XDocument doc = XDocument.Parse(xml);
var s = doc.Descendants("DestinationDocumentLibrary")
           .Where(e => e.Parent.Element("CategoryName")
                               .Value
                               .Equals("Checksheet and Lists"))
           .FirstOrDefault()
           .Value;

为了完整起见 - 获取一份 Linqpad 的副本以测试这类事情。

【讨论】:

    【解决方案3】:
    var values = doc.Descendants("DocumtentCategory")
                    .Where(x => x.Descendants("CategoryName")
                    .Where(x1 => x1.Value == "Checksheet and Lists").Any())
                    .Select(x => x.Descendants("DestinationDocumentLibrary").First().Value)
                    .ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多