Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Linq在XDocument中搜索具有特定属性的XElement_C#_Xml_Xaml_Linq To Xml_Xelement - Fatal编程技术网

C# 使用Linq在XDocument中搜索具有特定属性的XElement

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="

我有一个如下所示的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
属性的
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;