2016-10-15 6 views
1

私は自分のXMLの特定のノードをフェッチするのに苦労しています。 ノードがn番目のレベルに存在する場合と存在しない場合があります。 私は以下の私のXMLを共有していますLINQ for XMLを使用していくつかの特定のXMLノードをいくつかの親だけにフェッチする方法はありますか?

<?xml version="1.0" encoding="utf-8"?> 
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 
    <ItemGroup> 
    <Filter Include="Header Files"> 
     <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> 
     <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> 
    </Filter> 

    <Filter Include="Source Files - BT"> 
     <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> 
     <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> 
    </Filter> 

    <Filter Include="Source Files - BT\TreeViewsnTraversals"> 
     <UniqueIdentifier>{b685be7e-9d62-4f78-817c-def75db39d24}</UniqueIdentifier> 
    </Filter> 
    </ItemGroup> 

    <ItemGroup> 
    <ClCompile Include="..\4_Trees\SizeofBTree_Iterative.cpp"> 
     <Filter>Source Files - BT\TreeProperties</Filter> 
    </ClCompile> 
    <ClCompile Include="..\4_Trees\SizeofBTree_Recursive.cpp"> 
     <Filter>Source Files - BT\TreeProperties</Filter> 
    </ClCompile> 
    <ClCompile Include="..\4_Trees\LevelOrder_Left2Right.cpp"> 
     <Filter>Source Files - BT\TreeViewsnTraversals</Filter> 
    </ClCompile> 
    <ClCompile Include="..\4_Trees\LevelOrder_Right2Left.cpp"> 
     <Filter>Source Files - BT\TreeViewsnTraversals</Filter> 
    </ClCompile> 
    <ClCompile Include="..\4_Trees\PrintLeaftoNode.cpp"> 
     <Filter>Source Files - BT\TreeViewsnTraversals</Filter> 
    </ClCompile> 
    <ClCompile Include="..\4_Trees\VerticalOrderSUM.cpp"> 
    </ItemGroup> 
</Project> 

あなたが見ることができるように(対応する「フィルター」ノードと一緒に)唯一の「ClCompile」ノードに

をフェッチするためにどのように、これはClCompileはとして存在しています"ItemGroup"の子孫ノードとItemGroupにはClCompileが含まれていてもいなくてもかまいません。

C#の構文でXML用にLINQを使用しようとしましたが、失敗しました。

XElement filterxml = XElement.Load(filterfilepath); 
var sourcefiles = filterxml.Elements("Project").Elements("ItemGroup").Elements("ClCompile"); 

どうすればよいですか?

答えて

2

はちょうどあなたが必要とするすべての

var filter = nodes[i].Element(ns + "Filter"); 
+0

おかげで、フィルタエレメントを取得するには、デフォルトのXML名前空間

var xDoc = XDocument.Load(filename); XNamespace ns = xDoc.Root.GetDefaultNamespace(); //OR XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003"; var nodes = xDoc.Descendants(ns + "ClCompile").ToList(); 

を使用することを忘れないでください。これは動作します。 XNamespaceについてもっと詳しく説明できますか? –

関連する問題