从子节点查询xml父节点属性

我正在使用一个类似于这样的XML:

<?xml version="1.0" encoding="utf-8"?> <Results> <Pattern Name="Substitution"> <TestList> <Test> <Inputs> <Variable Name="A" Value="-1" /> <Variable Name="B" Value="20" /> </Inputs> <Outputs> <Variable Name="A" Value="-1" /> <Variable Name="B" Value="20" /> </Outputs> </Test> <Test> <Inputs> <Variable Name="A" Value="-1" /> <Variable Name="B" Value="20" /> </Inputs> <Outputs> <Variable Name="A" Value="-1" /> <Variable Name="B" Value="20" /> </Outputs> </Test> </TestList> </Pattern> <Pattern Name="MinMax"> <TestList> <Test> <Inputs> <Variable Name="A" Value="-1" /> <Variable Name="B" Value="20" /> </Inputs> <Outputs> <Variable Name="A" Value="-1" /> <Variable Name="B" Value="20" /> </Outputs> </Test> <Test> <Inputs> <Variable Name="A" Value="-1" /> <Variable Name="B" Value="20" /> </Inputs> <Outputs> <Variable Name="A" Value="-1" /> <Variable Name="B" Value="20" /> </Outputs> </Test> </TestList> </Pattern> </Results> 

我正在使用linq和excel interop将testing值写入Excel工作表。

 var tests = from test in document.Descendants("Test").Descendants("Inputs") select new { inputNames = test.Elements("Variable").Attributes("Name") }; foreach (var test in tests) { valueRow = valueMatch.Row; foreach (var inputName in test.inputNames) { if (valueSection.Find(inputName.Value, Missing.Value, Missing.Value, XlLookAt.xlWhole) != null) { workSheetTwo.Cells[valueRow, valueColumn] = inputName.NextAttribute.Value; ++valueRow; } } ++valueColumn; } 

写入Excel工作表的值工作正常,但我也需要根据它所在的模式名称来写入不同单元格背景颜色的值。(例如,如果模式名称=“replace”则为蓝色,如果模式名称= “MINMAX”)。 是不是可能从“inputName”获取模式名称的值? 我尝试使用inputName.Parent.Element("Pattern").Attribute("Name").Value ..但是,这将返回一个exception。 什么是正确的方法来做到这一点? 任何帮助,将不胜感激。 提前致谢。

你靠近,而不是Element("Pattern")调用Ancestors("Pattern").First()像这样…

 inputName.Parent.Ancestors("Pattern").First().Attribute("Name").Value 
 var tests = from p in xdoc.Descendants("Pattern") from input in p.Descendants("Test").Elements("Inputs") select new { Pattern = p.Attribute("Name").Value, Variables = input.Elements("Variable").Attributes("Name") };