简体   繁体   中英

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>
</Project>

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();

PS this approach doesn't require check against null every variable, eg:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM