using XElement to query for a node in namespace

心不动则不痛 提交于 2019-12-01 15:07:40

问题


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>

This fails miserably:

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?

Thanks.


回答1:


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

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

Personally I would usually go this route rather than XPath especially if namespaces are involved.



来源:https://stackoverflow.com/questions/4857172/using-xelement-to-query-for-a-node-in-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!