【问题标题】:Search through XDocument for XElement with certain Attribute using Linq使用 Linq 在 XDocument 中搜索具有特定属性的 XElement
【发布时间】:2015-11-20 15:25:29
【问题描述】:

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

但这不起作用,没有结果。请指教。

【问题讨论】:

    标签: c# xml xaml linq-to-xml xelement


    【解决方案1】:

    几个问题。您告诉Descendants() 查找具有本地名称Window 的元素,您应该告诉它查找具有本地名称TabItem 的元素(您实际想要的项目)。

    其次,如果你有一个没有x:Name 属性的TabItem,你会得到一个NullReferenceException;您会尝试在空引用上获取 Value 字段,因此您应该将 Attribute() 的返回值转换为字符串并进行比较。

    这是工作选择:

    IEnumerable<XElement> result = from myElems in doc.Descendants(xmlns + "TabItem")
                                   where (string)myElems.Attribute(xaml + "Name") == "mainTab"
                                   select myElems;
    

    【讨论】:

    • 非常感谢楼主。你让我的生活变得更好:)
    猜你喜欢
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    相关资源
    最近更新 更多