2011-07-29 16 views
1

LINQを初めて使用しています。 LINQを使用して、特定の値を特定のstringに取得したいと考えています。私は、以下の書式設定を含むXMLドキュメント(files.xml)を持っています。ノード内の指定された文字列値のLINQ検索

<?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」の値を盗んでください。

上記の例では、「チェックシートとリスト」はパラメータ(文字列)として渡され、LINQクエリに動的に渡されます。

質問が明確で、多くのおかげで、

+0

3つすべてがうまく動作しますが、以下のコメントで私が言及した理由で@ Timを選んだ。 – Chin

答えて

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です。

+0

上記の3つの答えがすべて答えてくれます。私は答えとして@ティムの答えをマークしています。それは正確に私が何をしているかの方に向いているようです。 – Chin

0
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

これは素敵ではないかもしれないが、動作するように表示されます。

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

とちょうど完全性の仕方によっては - これは非常に種類のものをテストするためLinqpadのコピーを取得します。

関連する問題