使用XElement解析XUnit XML文件如何获取failure节点下的message内容
问题原因
你之前的写法存在两个核心问题:
message不是test节点的属性,是test节点下failure子节点的子元素,Attribute()方法仅能获取节点的属性值,无法获取嵌套子元素的内容。- 你当前获取
test节点的查询逻辑有误:XElement.Elements()仅返回当前节点的直接子节点,你加载的根节点是<assemblies>,直接子节点只有<assembly>,因此你原来的写法实际无法查询到嵌套在下层的<test>节点。
修正后的代码实现
private static List<TestResults> GetTestAutomationExecutionResult(string filePath) { List<TestResults> testResults = new List<TestResults>(); XElement xelement = XElement.Load(filePath); // 用Descendants查找所有层级下的test节点 IEnumerable<XElement> results = xelement.Descendants().Where(e => e.Name.LocalName == "test"); foreach (var result in results) { string testResult = result.Attribute("result")?.Value ?? string.Empty; string failMsg = string.Empty; if (testResult == "Fail") { // 先取failure子节点,再取其下的message子元素的内容 var failureNode = result.Descendants().FirstOrDefault(e => e.Name.LocalName == "failure"); if (failureNode != null) { var msgNode = failureNode.Descendants().FirstOrDefault(e => e.Name.LocalName == "message"); failMsg = msgNode?.Value ?? string.Empty; // 如果需要同时取堆栈信息,加这行即可 // var stackNode = failureNode.Descendants().FirstOrDefault(e => e.Name.LocalName == "stack-trace"); // string stackTrace = stackNode?.Value ?? string.Empty; } } testResults.Add(new TestResults(testResult, failMsg)); } return testResults; }
补充说明
XML中的CDATA内容会被XElement自动解析为纯文本,不需要额外做转义处理,你拿到的failMsg就是直接可读的断言失败信息。代码中增加了空值判断逻辑,避免部分节点缺失时抛出空引用异常。
内容的提问来源于stack exchange,提问作者lawcrens
相关产品推荐
相关产品推荐

