简体   繁体   English

如何在XML的子子节点中查找属性的值?

[英]How to find value of an attribute in a sub child node of an XML?

I have a XML which has the following structure: 我有一个具有以下结构的XML:

<Results>
<TestResultAggregation testName="MyOrder">
  <Counters error="0" failed="1" timeout="0" aborted="0" inconclusive="0"/>
  <InnerResults>
    <UnitTestResult testName="TestMethod3" outcome="Failed">
      <Output>
        <ErrorInfo>
          <Message>Assert.Fail failed. </Message>
          <StackTrace>
            at Random.UnitTest1.TestMethod3()
          </StackTrace>
        </ErrorInfo>
      </Output>
    </UnitTestResult>
    <UnitTestResult testName="TestMethod2" outcome="Passed">
      <Output>
      </Output>
    </UnitTestResult>
  </InnerResults>
</TestResultAggregation>

When the result of 'outcome' attribute in 'UnitTestResult' is 'failed', I have to display the value of 'ErrorInfo' and 'StackTrace' nodes too. 当“ UnitTestResult”中“结果”属性的结果为“失败”时,我也必须显示“ ErrorInfo”和“ StackTrace”节点的值。 The catch here is that the above schema is not fixed . 这里要注意的是, 上面的模式不是固定的 For eg, 例如

<Results>
<UnitTestResult testName="TestMethod3" outcome="Failed">
      <Output>
        <ErrorInfo>
          <Message>Assert.Fail failed. </Message>
          <StackTrace>
            at Random.UnitTest1.TestMethod3()
          </StackTrace>
        </ErrorInfo>
      </Output>
    </UnitTestResult>
    <UnitTestResult testName="TestMethod2" outcome="Passed">
      <Output>
      </Output>
    </UnitTestResult>

The above schema can also be generated dynamically. 上述架构也可以动态生成。

How to write a code for the above requirement in C#?? 如何在C#中为上述要求编写代码?

Use LINQ2XML with Descendants method.. 将LINQ2XML与Descendants方法一起使用。

XDocument doc=XDocument.Parse(xmlstr);
var result=doc.Descendants().Elements("UnitTestResult")
                   .Where(x=>x.Attribute("outcome").Value=="Failed")
                   .Select(x=>
                    new
                    {
                         Message=x.Element("Output")
                                  .Element("ErrorInfo")
                                  .Element("Message").Value,
                         StackTrace=x.Element("Output")
                                     .Element("ErrorInfo")
                                     .Element("StackTrace").Value
                    });

Now you can iterate over result 现在您可以遍历result

foreach(var error in result)
{
    error.Message;
    error.StackTrace;
}
if (document.ToString().Contains(@"<UnitTestResult testName=""TestMethod2"" outcome=""failed"">"))
{

}

This won't be a popular answer I know. 我知道这不是一个流行的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM