我试图从一个看起来像这样的csproj文件中提取一个节点,但是无法让它工作 – 大概是因为名称空间声明.
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build"> <PropertyGroup> <RegisterForComInterop>true</RegisterForComInterop>
这失败了:
XDocument cpo = XDocument.Load(file); XmlNamespaceManager nsm = new XmlNamespaceManager(new NaMetable()); nsm.AddNamespace("x","http://schemas.microsoft.com/developer/msbuild/200"); IEnumerable<XElement> list3 = cpo.XPathSelectElements("//x:RegisterForComInterop[.='true']",nsm);
有什么想法吗?
谢谢.
解决方法
你真的想用XPath吗?在LINQ to XML中使用名称空间非常简单:
XDocument cpo = XDocument.Load(file); XNamespace x = "http://schemas.microsoft.com/developer/msbuild/2003"; var elements = cpo.Descendants(x + "RegisterForComInterop") .Where(x => (string) x == "true");
或者如果您确信每个RegisterForComInterop都有一个合适的布尔值,您可以使用explicit XElement
to bool
conversion:
XDocument cpo = XDocument.Load(file); XNamespace x = "http://schemas.microsoft.com/developer/msbuild/2003"; var elements = cpo.Descendants(x + "RegisterForComInterop") .Where(x => (bool) x);
就个人而言,我通常会走这条路而不是XPath,尤其是涉及名称空间时.