gpt4 book ai didi

c# - 如何提取 XML 文件中每次出现的标签

转载 作者:行者123 更新时间:2023-11-30 22:05:37 26 4
gpt4 key购买 nike

我有以下 XML 文件:

<queryResponse xmlns="">
<querySubjectResponse xmlns="">
...
<report>
<informationReported>
<aar>
<narrative>THIS IS A TEST NARRATIVE</narrative>
</aar>
</informationReported>
...
<statement>
<subjectStatement>
<statement>THIS IS A TEST STATEMENT</statement>
</subjectStatement>
</statement>
...
</report>
...
<report>
<informationReported>
<aar>
<narrative>THIS IS A TEST NARRATIVE2</narrative>
</aar>
</informationReported>
...
<statement>
<subjectStatement>
<statement>THIS IS A TEST STATEMENT2</statement>
</subjectStatement>
</statement>
...
</report>
...
<report>
<informationReported>
<aar>
<narrative>THIS IS A TEST NARRATIVE3</narrative>
</aar>
</informationReported>
...
<statement>
<subjectStatement>
<statement>THIS IS A TEST STATEMENT3</statement>
</subjectStatement>
</statement>
...
</report>
...
</querySubjectResponse>
</queryResponse>

我正在查看 LINQ to XML,但不确定如何实现它。我想保存叙述,对于每个叙述,将语句保存到一个数组中以备后用。

例子:

THIS IS A TEST NARRATIVE
THIS IS A TEST STATEMENT

THIS IS A TEST NARRATIVE2
THIS IS A TEST STATEMENT2

THIS IS A TEST NARRATIVE3
THIS IS A TEST STATEMENT3

如何实现?

我正在使用 XDocument 加载文件:

XDocument X = XDocument.Load("myfile.xml");
var main = x.Element("queryResponse").Element("querySubjectResponse").Element("report").Element("informationReported").Element("aar");

我正在尝试通过此链接获取答案:Linq to XML

最佳答案

假设每份报告都有叙述和可选陈述,这应该对您有用:

XElement root = XElement.Load(file);
List<string> list = root.Descendants("report")
.SelectMany(report =>
{
List<string> sub = new List<string>();
sub.Add(report.Descendants("narrative").First().Value);
string statement = (string)report.Descendants("statement")
.FirstOrDefault(s => s.Elements().Any() == false);
sub.Add(statement ?? "NULL");
return sub;
})
.ToList();

如果您想要单独列表中的叙述和陈述,请改为这样做:

var list = root.Descendants("report")
.Select(report => new
{
Narrative = report.Descendants("narrative").First().Value,
Statement = ((string)report.Descendants("statement")
.FirstOrDefault(s => s.Elements().Any() == false))
?? "NULL"
})
.ToList();

关于c# - 如何提取 XML 文件中每次出现的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24268245/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com