我正在尝试从看起来像这样的 csproj 文件中提取一个节点,但无法让它工作 - 大概是因为命名空间声明.
i'm trying to pull out a node from a csproj file that looks like this, but can't get it to work - presumably because of the namespace declaration.
<?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);
请问大家有什么想法吗?
Anyone any ideas please?
谢谢.
你真的要为此使用 XPath 吗?在 LINQ to XML 中使用命名空间真的很容易:
Do you really want to use XPath for this? It's really easy to use namespaces within 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 都将具有适当的布尔值,您可以使用 explicitXElement
到 bool
转换:
or if you're absolutely convinced that every RegisterForComInterop will have an appropriate Boolean value you can use the 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尤其是.
Personally I would usually go this route rather than XPath especially if namespaces are involved.
这篇关于使用 XElement 查询命名空间中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!