通过linq检索和XDocuments属性值
本文关键字:属性 XDocuments linq 检索 通过 | 更新日期: 2023-09-27 17:58:17
在此处查找正确的select语句时遇到问题
我有以下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();
但这不起作用,查询为空
因为属性的名称是Path
而不是privatePath
。此外,您可以使用显式强制转换,然后不需要null检查:
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名称空间的更多详细信息:使用xml名称空间