2014-04-14 53 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