使用XElement查询名称空间中的节点 [英] using XElement to query for a node in namespace
问题描述
我正在尝试从看起来像这样的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);
请问有什么想法吗?
谢谢.
推荐答案
您真的要为此使用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都将具有适当的布尔值,则可以使用显式XElement
到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查询名称空间中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!