通过Linq到XML获取父节点的属性值 [英] Get attribute value of parent node by Linq to XML

查看:68
本文介绍了通过Linq到XML获取父节点的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Linq到XML解析XML文件时遇到问题.

I have a problem parsing a XML file using Linq to XML.

我的XML结构如下:

<Module>
  <Variable Name="Variable1" Value="True" />
  <Variable Name="Variable2" Value="True" />
  <Variable Name="Variable3" Value="True" />
  </Task>
  <Task Name="Task1">
    <Variable Name="Task1Variable1" Value ="True" />
    <Variable Name=" Task1Variable2" Value ="True" />
  </Task>
  <Task Name="Task2">
    <Variable Name="Task2Variable1" Value ="True" />
    <Variable Name=" Task2Variable2" Value ="True" />
  </Task>
</Module>

我打算做的是获取每个变量名"属性的值. 因此,对于直接位于节点模块下的元素,使用

What I intend to do is to get the value of each Variable Name attribute. So for the elements that are directly under the node Module it works fine with

var variables = (from cfg in _xElements.Descendants("Module").Elements("Variable")
                                       select cfg.Attribute("Name"));

问题开始于Task节点下的Variable Name属性,因为我还需要有关Task Name的信息.

The problem starts with the Variable Name attributes that are under the Task nodes because I also need the information about the Task Name.

所以我想得到的是有关变量名称的信息以及有关作为变量元素的父节点的任务名称的信息.

So what I would like to get is the information about the Variable name plus the information about the Task Name that is the parent node of the variable element.

有没有办法用Linq做到这一点?

Is there a way to get this done with Linq?

推荐答案

您可以使用XElement的父属性

You can use parent property of XElement

var variables = (from cfg in _xElements.Descendants("Variable")
                                       select new
{
  TaskName = cfg.Parent.Name == "Task"? cfg.Parent.Attribute("Name"):null,   
  VariableAttribute = cfg.Attribute("Name")
});

这篇关于通过Linq到XML获取父节点的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆