Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath and *.csproj

Tags:

c#

xpath

csproj

I am for sure missing some important detail here. I just cannot make .NET's XPath work with Visual Studio project files.

Let's load an xml document:

var doc = new XmlDocument();
doc.Load("blah/blah.csproj");

Now execute my query:

var nodes = doc.SelectNodes("//ItemGroup");
Console.WriteLine(nodes.Count); // whoops, zero

Of course, there are nodes named ItemGroup in the file. Moreover, this query works:

var nodes = doc.SelectNodes("//*/@Include");
Console.WriteLine(nodes.Count); // found some

With other documents, XPath works just fine. I am absolutely puzzled about that. Could anyone explain me what is going on?

like image 552
catbert Avatar asked Sep 19 '10 08:09

catbert


People also ask

What does .csproj mean?

Files with CSPROJ extension represent a C# project file that contains the list of files included in a project along with the references to system assemblies.

What is Csproj file used for?

csproj file to determine the packages to install from Nuget. To compile an ASP.NET application, the compiler needs information such as the version of the dotnet framework, the type of the application, etc. A . csproj file stores all this information that allows dotnet to build and compile the project.


1 Answers

You probably need to add a reference to the namespace http://schemas.microsoft.com/developer/msbuild/2003.

I had a similar problem, I wrote about it here. Do something like this:

XmlDocument xdDoc = new XmlDocument();
xdDoc.Load("blah/blah.csproj");

XmlNamespaceManager xnManager =
 new XmlNamespaceManager(xdDoc.NameTable);
xnManager.AddNamespace("tu",
 "http://schemas.microsoft.com/developer/msbuild/2003");

XmlNode xnRoot = xdDoc.DocumentElement;
XmlNodeList xnlPages = xnRoot.SelectNodes("//tu:ItemGroup", xnManager);
like image 191
Naeem Sarfraz Avatar answered Oct 29 '22 20:10

Naeem Sarfraz