【发布时间】:2019-07-23 10:00:54
【问题描述】:
我的目标是从 XML 中提取数据。但是我有一些相当复杂的 XML,它们不容易转换为 C 语言类。
XML 如下所示:
<group.........>
<suite....>
<properties>
<property name=....../>
</properties>
<suite type="test">
<suite type="test1">
<suite...>
<suite...>
<suite...>
<case id="1000" name="example">
<properties>
<property ...../>
</properties>
</case>
<case.......>
<properties>
<property ...../>
</properties>
</case>
<case>
<properties>
<property .... />
</properties>
</case>
</suite>
</suite>
</suite>
</suite>
</suite>
</suite>
</group>
我使用了一个在线的 xml to c sharp convert 来创建类,但它似乎不能正确处理 XML 结构。
更新:
XML 来自 NUNIT3。它是写入 XML 文档的 UNIT3 控制台的结果。
更新 2:
我可以使用以下代码提取数据 - 不知道是否有更优雅的解决方案:
XElement resultFile = XElement.Load($"{resultFilePathList}");
var dataFromXML = (
from data in resultFile.Descendants("case")
select new
{
caseid = data.Attribute("id").Value,
name = data.Attribute("fullname").Value,
result = data.Attribute("result").Value,
duration = data.Attribute("duration").Value
}
);
【问题讨论】:
-
将 XML 复制到剪贴板,然后在 VS 中选择 Edit/Paste Special/Paste XML as classes。除了设计你的 XML 文件的人没有创建一个有效的文件。
-
@Neil 试过它创建了很多类,比如 suitesuitesute 和 suitesuite 等多个类
-
除非你能让这个 XML 的创建者“做得更好”,否则你将不得不在 XmlReader csharp.net-tutorials.com/xml/… 的帮助下“手动”解析那个 XML
-
@Neil,XmlReader 是做什么用的?
-
我会在
XmlReader之前使用 LINQ-to-XML 和XDocument。
标签: c# xml deserialization