[英]Linq to XML Get parent element attribute value by querying it's children
[英]Get attribute value of parent node by Linq to XML
我在使用Linq到XML解析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>
我打算做的是获取每个“变量名”属性的值。 因此,对于直接位于节点模块下的元素,它可以与
var variables = (from cfg in _xElements.Descendants("Module").Elements("Variable")
select cfg.Attribute("Name"));
问题开始于Task节点下的Variable Name属性,因为我还需要有关Task Name的信息。
所以我想得到的是有关变量名称的信息以及有关作为变量元素的父节点的任务名称的信息。
有没有办法用Linq做到这一点?
您可以使用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")
});
在这种情况下,后代将无法工作。 尝试完整的解决方案
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml =
"<Module>" +
"<Variable Name=\"Variable1\" Value=\"True\" />" +
"<Variable Name=\"Variable2\" Value=\"True\" />" +
"<Variable Name=\"Variable3\" Value=\"True\" />" +
"<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>";
XDocument doc = XDocument.Parse(xml);
var results = doc.Elements("Module").Select(m => new {
variables = m.Elements("Variable").Select(n => new {
name = (string)n.Attribute("Name"),
value = (string)n.Attribute("Value")
}).ToList(),
tasks = m.Elements("Task").Select(o => new {
name = (string)o.Attribute("Name"),
variables = o.Elements("Variable").Select(p => new {
name = (string)p.Attribute("Name"),
value = (string)p.Attribute("Value")
}).ToList()
}).ToList()
}).FirstOrDefault();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.