使用LINQ从XML中提取属性

时间:2010-11-23 14:02:24

标签: c# .net linq linq-to-xml

我有以下XML文件(它实际上是VS2010 dbproj文件)

<?xml version="1.0" enconding="utf-8"?>
<Project.....>
<propertyGroup>
....
</PropertyGroup>
<ItemGroup>
 <Build Include = "Schema Objects\Schemas\dbo\Programmability\Stored Procedures\foo.sql>
 </Build>
</ItemGroup>
</Project>

我想使用LINQ to XML来提取存储过程的所有Build元素。 我有以下代码,似乎不起作用:

var doc = XDocument.Load(filePath);
var elements = doc.Descendants("Build").Where( x => x.Attribute("Include").Value.Contains("Stored Procedure")).ToList();

提取属性值的正确方法是什么?

感谢您的回复!事实证明,在Project标签中指定了一个名称空间,我省略了它。这就是我得到0结果的原因。

2 个答案:

答案 0 :(得分:2)

var doc = XElement.Parse(xml);
// or
var doc = XDocument.Load(path);

var q = from e in doc.Descendants("Build")
        from a in e.Attributes("Include")
        where a.Value.Contains("Stored Procedure")
        select e;

var list = q.ToList();

P.S。这种方法不需要检查每个变量的null,例如:

var q = from e in doc.Descendants("Build")
        where e != null
        from a in e.Attributes("Include")
        where a != null && a.Value != null && a.Value.Contains("Stored Procedure")
        select e;

答案 1 :(得分:0)

一旦你修复了XML(你错过了一个结束语,并且那里有不匹配的标签),它就可以了。在LINQPad中测试

string xml = 
    "<Project>"+
    "<PropertyGroup>" +
    "</PropertyGroup>" +
    "<ItemGroup>" +
    "<Build Include = \"Schema Objects\\Schemas\\dbo\\Programmability\\Stored Procedures\\foo.sql\">"+
    "</Build>"+
    "</ItemGroup>"+
    "</Project>";

var doc = XDocument.Parse(xml);
var elements = doc.Descendants("Build").Where (x => x.Attribute("Include").Value.Contains("Stored Procedure")).ToList();
elements.Dump();

结果是:

<Build Include="Schema Objects\Schemas\dbo\Programmability\Stored Procedures\foo.sql">    </Build>

如果你只是想获得价值,试试这个:

var element2 = doc.Descendants("Build").Where (x => x.Attribute("Include").Value.Contains("Stored Procedure")).Select (x => x.Attribute("Include").Value);
element2.Dump();

编辑 - 这也有效:

var element3 = doc.Descendants("Build").Select(x=>x.Attribute("Include")).Where(y=>y.Value.Contains("Stored Procedure")).FirstOrDefault().Value;