0

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.

1
  • 2
    That looks okay to me. "Doesn't seem to work" is pretty vague - care to describe what actually happens? Any chance it's a namespace problem? Commented Nov 23, 2010 at 14:04

2 Answers 2

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. 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;
Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.