简体   繁体   中英

LINQ to XML query from querystring

I need to create xml files based on querystring values.

My xml file:

<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>

So if i type ?filter=Books,Paper i need to select Product where Category contains value from querystring.

Then if i type ?filter=Books,Paper&filter2=Drama i still need Product where Category contains filter1 but if Product element contains SubCategory that contains filter2 i need to select just those.

So with: ?filter=Books,Paper&filter2=Drama i need to get xml that looks like this:

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

Also some products may have empty SubCategory element. I don't know if that is important.

My query looks like this:

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
                        };

This is selecting all Product elements where filter1 contains SubCategory .

So can anyone point me in to right direction on how to write this query.

Thanks.

This should get you started in the right direction, it will find all products where the Category element is either Book or Paper

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM