2011-06-27 31 views
0

我需要基於查詢字符串值創建xml文件。從查詢字符串LINQ到XML查詢

我的XML文件:

<Products> 
<Product> 
    <Name>Name</Name> 
    <Category>Books</Category> 
    <SubCategory>Drama</SubCategory> 
</Product> 
<Product> 
    <Name>Name</Name> 
    <Category>Books</Category> 
    <SubCategory>Action</SubCategory> 
</Product> 
<Product> 
    <Name>Name</Name> 
    <Category>Paper</Category> 
    <SubCategory></SubCategory> 
</Product> 

所以,如果我輸入?filter=Books,Paper,我需要選擇Product其中Category包含查詢字符串值。

然後,如果我輸入?filter=Books,Paper&filter2=Drama我仍然需要Product其中Category包含filter1但如果Product元素包含SubCategory包含filter2我需要選擇只是那些。

所以有:?filter=Books,Paper&filter2=Drama我需要得到XML,看起來像這樣:

<Products> 
    <Product> 
     <Name>Name</Name> 
     <Category>Books</Category> 
     <SubCategory>Drama</SubCategory> 
    </Product> 
    <Product> 
     <Name>Name</Name> 
     <Category>Paper</Category> 
     <SubCategory></SubCategory> 
    </Product> 
</Products> 

也有一些產品可能有空SubCategory元素。我不知道這是否重要。

我的查詢看起來是這樣的:

var items = from el in SimpleStreamAxis(esysPath, "Product") 
         where filter.Contains(el.Element("Category").Value.Trim()) 
         where filter1.Contains(el.Element("SubCategory").Value.Trim()) 
         select new 
         { 
          ProductID = el.Element("ID").Value, 
          Name = el.Element("Name").Value, 
          Price = el.Element("Price").Value, 
          Picture = el.Element("Picture").Value 
         }; 

這是選擇所有Product元素,其中包含filter1SubCategory

所以任何人都可以指出我如何寫這個查詢的正確方向。

謝謝。

回答

0

這應該讓你在正確的方向開始,它會發現所有的產品,該Category元素是BookPaper

List<string> categories = new List<string() {"Book", "Paper"}; 
XDocument doc = XDocument.Parse("Your xml string"); 
var products = doc.Descendants("Product") 
       .Where(el => categories.Contains(el.Element("Category").Value));