Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

c# - using XElement to query for a node in namespace

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...