来自querystring的LINQ到XML查询

本文关键字:XML 查询 LINQ querystring 来自 | 更新日期: 2023-09-27 18:00:27

我需要基于查询字符串值创建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元素包含包含filter2SubCategory,我需要仅选择这些。

因此,对于:?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
                        };

这是选择filter1包含SubCategory的所有Product元素。

所以,有人能为我指出如何编写这个查询的正确方向吗。

谢谢。

来自querystring的LINQ到XML查询

这应该会让你朝着正确的方向开始,它会找到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));