我的Linq到Xml查询中的重复节点问题

时间:2012-10-09 14:10:51

标签: linq-to-xml

我设法从文件中查询XML文档,但是我只需要提取一个"过滤器"来自此XML片段的节点(当然还有其子节点)基于" id"这是传递给我的C#方法:

  <outBound>
   <body>
       <filter id="1">
          <name>A. All Portfolios</name>
          ...
          <query>
              ...
          </query>
       </filter>
       <filter id="2">
          <name>A. Busines Portfolios</name>
          ...
          <query>
              ...
          </query>
       </filter>
   </body>
  </outBound>

我从我下载的一些MS样本中建模了我的L2X代码,但是我怎么只是简单地过滤?

        XDocument document = XDocument.Load(Server.MapPath("~/xml/portfolioFilters.xml"));  //portfolioFiltersResponse  //portfolioFilters            
        var portFilterAll = from x in document.Descendants()
                         where x.Name == "filter"
                         select x;

        var portFilt = new XElement("filter",
                            from x in document.Descendants("filter")
                            where (string)x.Element("name") == filterName
                            select new XElement("filter",
                                        x.Attribute("id"),
                                        x.Element("name"),
                                        x.Element("type"),
                                        x.Element("userId"),
                                        x.Element("security"),
                                        x.Element("queries")
                                       ));

但是,我最终得到的结果是EXTRA&#34;过滤器&#34;像这样的节点:

   <filter>
     <filter id="1">
       <name>A. All Portfolios</name>
       ...
       <query>
          ...
       </query>
     </filter>
   </filter>

有人可以帮助我稍微调整一下,以便只拉出&#34;过滤器&#34;我需要的节点,基于&#34; id&#34;属性?

谢谢你。 鲍勃

1 个答案:

答案 0 :(得分:1)

您可以创建顶级滤镜元素,然后选择并创建子滤镜元素。 如何选择你需要的东西:

var portFilt = from x in document.Descendants("filter")
               where (string)x.Element("name") == filterName
               select x;