2012-10-09 24 views
0

我已經設法從一個文件中查詢XML文檔,但是我只需要從這個XML片段(以及它的子節點當然)中只抽取一個「過濾器」節點,在此基礎上傳遞到我的C#方法中的「ID」:我的Linq XML查詢中的重複節點問題

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

然而,什麼我得到我的最終結果是在頂部一個額外的「過濾器」節點是這樣的:

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

有人可以幫助我在這調整了一下,只拉我需要基於「id」屬性的「過濾器」節點?

謝謝。 Bob

回答

1

您創建頂級過濾元素並選擇並創建子過濾元素。 如何只選擇你所需要的是這樣的:

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

VAR pfFilter =從X在document.Descendants() 其中 x.Name == 「過濾器」 && x.Element( 「名」)。 Value.Equals(filterName) select x; –

+0

你如何讓你的代碼像這樣突出顯示? thx –

+0

通常只是格式化它會突出顯示它。如果你需要更多的細節,請看這裏:http://stackoverflow.com/editing-help#syntax-highlighting。我通過添加'select x;'來固定查詢 - 您想使用'(string)x.Element(「name」)'而不是'x.Element(「name」)。值'避免NullReferenceExceptions如果元素與名稱不存在。 (爲了標記內聯代碼,你使用反引號(')) – Pawel