2014-04-14 109 views
0

「M爲這裏找出正確的select語句檢索和XDocuments通過LINQ屬性值

一個問題,我有以下XML

<configuration> 
    <other sections> 
    <runtime> 
    <Binding xmlns="urn:schemas-microsoft-com:asm.v1"> 
     <probing Path="some path string" /> 
    </Binding> 
    <Concurrent enabled="false" /> 
    </runtime> 
    <other sections> 
</configuration> 

我試着做一個選擇,我檢索路徑串。值

到目前爲止,我有這個

XDocument xdoc = XDocument.Load(XmlfilePath); 

var query = (from c in xdoc.Descendants("probing") 
where c.Attribute("Path") != null 
select c.Attribute("Path").Value).FirstOrDefault(); 

但這不起作用,查詢爲空

回答

3

因爲你的屬性的名稱是PathprivatePath。也可以使用顯式轉換,然後你不需要空檢查:

var query = (from c in xdoc.Descendants("probing") 
      select (string)c.Attribute("Path")).FirstOrDefault(); 

更新:似乎你的元素有一個命名空間,所以你需要指定這樣的命名空間:

XNamespace ns = "urn:schemas-microsoft-com:asm.v1"; 

var query = (from c in xdoc.Descendants(ns + "probing") 
      select (string)c.Attribute("Path")).FirstOrDefault(); 

你可能想看看文檔有關XML命名空間的更多細節:Working with XML Namespaces

+0

對不起,對於我在xml路徑中創建「privatePath」的示例,忘了更改代碼示例。 我剛剛嘗試過你的例子,但它仍然爲空查詢值 – Domitius

+0

@Domitius現在我看到名稱空間sorry.I更新我的答案再試一次。 –

+0

謝謝,這工作 – Domitius