我一直在努力获取XML的某些特定节点。 问题是节点可能存在或可能不存在于第n级。 我在下面分享了我的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>
如何仅获取&#34; ClCompile&#34;节点(以及相应的&#34;过滤器&#34;节点)
正如您所看到的,这是ClCompile作为&#34; ItemGroup&#34;的后代节点。和ItemGroup可能包含也可能不包含ClCompile。
我尝试在C#语法中使用LINQ for XML,但我失败了!
XElement filterxml = XElement.Load(filterfilepath);
var sourcefiles = filterxml.Elements("Project").Elements("ItemGroup").Elements("ClCompile");
如何解决这个问题?
答案 0 :(得分:2)
不要忘记使用默认的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();
要获取Filter元素,您只需要
var filter = nodes[i].Element(ns + "Filter");