2011-01-31 8 views
5

このように見えるが、おそらくネームスペース宣言のために動作しないcsprojファイルからノードを引き出そうとしています。XElementを使用してネームスペース内のノードを照会します

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

誰でも任意のアイデアしてください?

ありがとうございました。

答えて

12

本当にこれにXPathを使用しますか?

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

を私は考えそれはXMLにLINQの中に名前空間を使用するのはとても簡単です名前空間が含まれている場合は、通常はXPath ではなく、となります。

+0

ブール値の文字列を100%期待しているので、最後の行を '.Where(x => bool.Parse(x.Value)) 'に置き換えます。 – Shimmy

+0

バッチ・パフォーマンスの場合、この選択はオーバーヘッドを削減します。 – Shimmy

+0

@Shimmy:ここではbool.Parseを使用しません。XMLについて知っている 'bool'への明示的な変換を使用します。編集します。 –

関連する問題