XPath和* .csproj

我肯定错过了一些重要的细节。 我只是不能使.NET的XPath与Visual Studio项目文件一起工作。

我们加载一个xml文档:

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

现在执行我的查询:

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

当然,文件中有名为ItemGroup的节点。 此外,此查询有效:

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

使用其他文档,XPath工作得很好。 我对此完全感到困惑。 谁能解释一下发生了什么事?

您可能需要添加对命名空间http://schemas.microsoft.com/developer/msbuild/2003的引用。

我有一个类似的问题,我在这里写了一下 。 做这样的事情:

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

查看根命名空间; 你必须包含一个xml-namespace管理器并使用像“// x:ItemGroup”这样的查询,其中“x”是你为root命名空间指定的别名。 并将经理传递给查询。 例如:

  XmlDocument doc = new XmlDocument(); doc.Load("my.csproj"); XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable); mgr.AddNamespace("foo", doc.DocumentElement.NamespaceURI); XmlNode firstCompile = doc.SelectSingleNode("//foo:Compile", mgr); 

我发布了一个LINQ / Xml版本:

http://granadacoder.wordpress.com/2012/10/11/how-to-find-references-in-ac-project-file-csproj-using-linq-xml/

但这是它的要点。 它可能不是100%完美……但它显示了这个想法。

我在这里发布代码,因为我在搜索答案时发现了这个(原始post)。 然后我厌倦了搜索并写下了我自己的。

  string fileName = @"C:\MyFolder\MyProjectFile.csproj"; XDocument xDoc = XDocument.Load(fileName); XNamespace ns = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003"); //References "By DLL (file)" var list1 = from list in xDoc.Descendants(ns + "ItemGroup") from item in list.Elements(ns + "Reference") /* where item.Element(ns + "HintPath") != null */ select new { CsProjFileName = fileName, ReferenceInclude = item.Attribute("Include").Value, RefType = (item.Element(ns + "HintPath") == null) ? "CompiledDLLInGac" : "CompiledDLL", HintPath = (item.Element(ns + "HintPath") == null) ? string.Empty : item.Element(ns + "HintPath").Value }; foreach (var v in list1) { Console.WriteLine(v.ToString()); } //References "By Project" var list2 = from list in xDoc.Descendants(ns + "ItemGroup") from item in list.Elements(ns + "ProjectReference") where item.Element(ns + "Project") != null select new { CsProjFileName = fileName, ReferenceInclude = item.Attribute("Include").Value, RefType = "ProjectReference", ProjectGuid = item.Element(ns + "Project").Value }; foreach (var v in list2) { Console.WriteLine(v.ToString()); }