[英]Search through XDocument for XElement with certain Attribute using Linq
我有一个看起来像这样的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="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 mainTab的XElement
TabItem。 这是我的代码的样子:
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;
但这是行不通的,没有结果。 请指教。
夫妻问题。 您要告诉Descendants()
寻找具有本地名称Window
的元素,应该告诉它寻找具有本地名称TabItem
的元素(您实际想要的项目)。
其次,如果您有一个没有x:Name
属性的TabItem
,则将获得NullReferenceException
。 您将尝试在空引用上获取“ Value
字段,因此您应将Attribute()
的返回值Attribute()
转换为字符串并进行比较。
这是工作选择:
IEnumerable<XElement> result = from myElems in doc.Descendants(xmlns + "TabItem")
where (string)myElems.Attribute(xaml + "Name") == "mainTab"
select myElems;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.