gpt4 book ai didi

c# - 在 C# 中使用 xdocument 从 xml 文件中提取特定数据

转载 作者:行者123 更新时间:2023-11-30 23:13:08 25 4
gpt4 key购买 nike

我正在尝试从我的 xml 文件中获取相关数据。因此,例如,我希望从 venue 元素中选择名为 Roker Park 的元素中的所有数据。我如何只选择该数据而不选择其余数据?这是我的 xdocument

<Funrun>
<Venue>
<Name>Roker Park</Name>
<Runner>
<Charity>Cancer Research</Charity>
<Firstname>Roger</Firstname>
<Lastname>Malibu</Lastname>
<Sponsorship>550</Sponsorship>
</Runner>
<Runner>
<Charity>Arthritis UK</Charity>
<Firstname>Adam</Firstname>
<Lastname>White</Lastname>
<Sponsorship>340</Sponsorship>
</Runner>
<Venue>
<Name>Victoria Park</Name>
<Runner>
<Charity>Against Malaria Foundation</Charity>
<Firstname>Rob</Firstname>
<Lastname>Tate</Lastname>
<Sponsorship>850</Sponsorship>
</Runner>
<Runner>
<Charity>Fred Follows Foundation</Charity>
<Firstname>Peter</Firstname>
<Lastname>Jackson</Lastname>
<Sponsorship>500</Sponsorship>
</Runner>
</Venue>
</Funrun>

到目前为止我得到的代码选择了所有场馆数据,所以我得到了 Victoria Parks 和 Rokers,这是我到目前为止得到的代码:

List<string> VenueNames = new List<string>();
List<string> VenueDataList = new List<string>();

var doc = XDocument.Load("XMLFile1.xml");
var doc2 = XDocument.Load("XMLFile2.xml");
var doc3 = XDocument.Load("XMLFile3.xml");

var combinedunique = doc.Descendants("Venue")
.Union(doc2.Descendants("Venue"))
.Union(doc3.Descendants("Venue"));

foreach (XElement element in combinedunique.DescendantsAndSelf("Venue"))
{
VenueNames.Add(element.Element("Name").Value.ToString());
}

if (Convert.ToString(lstboxVenues.SelectedItem) == VenueNames.ElementAt(0))
{
foreach (XElement element in combinedunique.DescendantsAndSelf("Firstname"))
{
VenueDataList.Add(element.Value);
}

for (int i = 0; i < VenueDataList.Count; i++)
{
lstboxVenueData.Items.Add(VenueDataList.ElementAt(i));
}
}

最佳答案

获取所有 field 名称:

List<strgin> VenueNames = combindedunique.Select(v => (string)v.Element("Name")).ToList();

输出:

[
"Roker Park",
"Victoria Park"
]

通过给定的场所名称获取名字:

string venueName = "Victoria Park"; // name you want to search by
List<string> VenueDataList =
combindedunique.Where(v => (string)v.Element("Name") == venueName)
.Elements("Runner")
.Select(r => (string)r.Element("Firstname"))
.ToList();

输出:

[
"Rob",
"Peter"
]

关于c# - 在 C# 中使用 xdocument 从 xml 文件中提取特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43765180/

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