开发者

Extracting attributes from XML using LINQ

I have the following XML file (it's actually VS2010 dbproj file)

<?xml version="1.0" enconding="utf-8"?>
<Project.....>
<propertyGroup>
....
</PropertyGroup>
<ItemGroup>
 <Build Include = "Schema Objects\Schemas\dbo\Programmability\Stored Procedures\foo.sql>
 </Build>
</ItemGroup>
</Projec开发者_运维技巧t>

I would like to use LINQ to XML to extract all Build elements that are Stored Procedures. I have the following code, which doesn't seem to work:

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

What is the right way of extracting the attribute values?

Thanks for the replies! It turned out that there was a namespace specified in the Project tag which I omitted. That's why I was getting 0 results back.


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. this approach doesn't require check against null every variable, e.g.:

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;


Once you fix the XML (you're missing a closing quote, and you have unmatched tags there), it works fine. Tested in 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();

Result is:

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

If you are just trying to get the value, try this:

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

EDIT - This works too:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜