我肯定在这里遗漏了一些重要的细节。我就是不能让.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工作得很好。我对此感到非常困惑。谁能给我解释一下这是怎么回事?
发布于 2010-09-19 16:38:53
您可能需要添加对名称空间http://schemas.microsoft.com/developer/msbuild/2003的引用。
我也遇到过类似的问题,我在here上写了这个问题。这样做:
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);发布于 2010-09-19 16:38:19
看一下根名称空间;您必须包含一个xml名称空间管理器并使用类似于"//x:ItemGroup“的查询,其中"x”是您为根名称空间指定的别名。并将管理器传递到查询中。例如:
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);发布于 2012-10-12 05:33:18
我在以下位置发布了一个LINQ / Xml版本:
http://granadacoder.wordpress.com/2012/10/11/how-to-find-references-in-a-c-project-file-csproj-using-linq-xml/
但这里是它的要点。它可能不是100%的perfect......but,但它表明了这一想法。
我在这里发布代码,因为我在搜索答案时发现了这个(原始帖子)。然后我厌倦了搜索,写了我自己的。
using System;
using System.Linq;
using System.Xml.Linq;
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());
}https://stackoverflow.com/questions/3745029
复制相似问题