开发者

LINQ search for a given string value within a node

I am new to using LINQ. I would like to use LINQ to retrieve a certain value to given string.I have a XML document (files.xml) that contains below formatting.

开发者_JAVA技巧
<?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>

Question

How do I retreive the value of "DestinationDocumentLibrary" as string for a "CategoryName" of "Checksheet and Lists" using LINQ.

In above example "Checksheet and Lists" is passed as a parameter (string) and will be dynamically passed to the LINQ query.

Hope the question is clear and many thanks in advance.


Give this a try:

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 is an XDocument containing your xml.


This may not be the nicest but it appears to work:

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

and just by way of completeness - get a copy of Linqpad for testing this very sort of thing.


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜