1

我正在使用与此类似的 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 互操作将测试中的值写入 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 工作表工作正常,但我还需要根据它所在的模式名称写入具有不同单元格背景颜色的值。(例如,如果 Pattern Name="Substitution" 则为蓝色,如果 Pattern Name= 则为黄色“最小最大”)。是否可以从“inputName”获取模式名称的值?我尝试使用inputName.Parent.Element("Pattern").Attribute("Name").Value.. 但这会返回异常。这样做的正确方法是什么?任何帮助,将不胜感激。提前致谢。

4

2 回答 2

1

你很亲密,而不是像这样Element("Pattern")打电话Ancestors("Pattern").First()......

inputName.Parent.Ancestors("Pattern").First().Attribute("Name").Value
于 2013-05-31T06:18:07.163 回答
0
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") };
于 2013-05-31T07:31:26.800 回答