【问题标题】:LINQ to XML query from querystring来自查询字符串的 LINQ to XML 查询
【发布时间】:2011-09-23 20:40:25
【问题描述】:

我需要根据查询字符串值创建 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&amp;filter2=Drama 我仍然需要Product 其中Category 包含filter1 但如果Product 元素包含SubCategory 包含filter2 我只需要选择那些。

因此:?filter=Books,Paper&amp;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 元素,其中filter1 包含SubCategory

那么任何人都可以为我指出如何编写此查询的正确方向。

谢谢。

【问题讨论】:

    标签: c# linq-to-xml


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多