C# 使用Linq在XDocument中搜索具有特定属性的XElement
我有一个如下所示的XML文档:C# 使用Linq在XDocument中搜索具有特定属性的XElement,c#,xml,xaml,linq-to-xml,xelement,C#,Xml,Xaml,Linq To Xml,Xelement,我有一个如下所示的XML文档: <Window x:Name="winName" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="My Window" SizeToContent="WidthAndHeight"> <Grid ShowGridLines="
<Window x:Name="winName" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="My Window" SizeToContent="WidthAndHeight">
<Grid ShowGridLines="true">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<GroupBox x:Name="grBox" Header="Main Group Box" Grid.Row="0" Grid.Column="0" Grid.RowSpan="1" Grid.ColumnSpan="1" />
<TabControl x:Name="tabControl" Grid.Row="1" Grid.Column="0" Grid.RowSpan="1" Grid.ColumnSpan="1">
<TabItem x:Name="mainTab" Header="Main Tab" />
</TabControl>
</Grid>
</Window>
但这不起作用,没有结果。请告知 两个问题。您告诉
子体()
要查找具有本地名称的元素窗口
,您应该告诉它查找具有本地名称的元素选项卡项
(您实际需要的项)
其次,如果您有一个没有x:Name
属性的TabItem
,您将得到一个NullReferenceException
;您将尝试在空引用上获取值
字段,因此您应该将属性()的返回值转换为字符串并进行比较
以下是工作选择:
IEnumerable result=来自文档子体中的myElems(xmlns+“TabItem”)
其中(字符串)myElems.Attribute(xaml+“Name”)=“mainTab”
选择髓鞘;
非常感谢您,大师。你让我的生活变得更好:)
XDocument doc = XDocument.Load(path);
XNamespace xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
XNamespace xaml = "http://schemas.microsoft.com/winfx/2006/xaml";
IEnumerable<XElement> result = from myElems in doc.Descendants(xmlns + "Window")
where myElems.Attribute(xaml + "Name").Value == "mainTab"
select myElems;