gpt4 book ai didi

c# - XDocument 节点中的 Foreach

转载 作者:太空宇宙 更新时间:2023-11-03 22:55:40 25 4
gpt4 key购买 nike

<tests>
<test id ="1">
<name> peter </name>
<age> 23 </age>
<informations> bla bla </informations>
</test>
<test id ="41">
<name> besd </name>
<age> 54 </age>
<informations> some other text </informations>
</test>
<test id ="57">
<name> john </name>
<age> 61 </age>
<informations> vintage </informations>
</test>
<test id ="67">
<name> claude </name>
<age> 11 </age>
<informations> motivation </informations>
</test>
</tests>

我设法在 XDocument xInformations 中获取了上述所有信息。

  List<string> testIds = new List<string>();
testIds = xInformations.Descendants("test").Select(x => (string)x.Attribute("id")).ToList();

现在,我想使用 foreach 来读取并保存每个 id 的所有信息:

foreach (string extId in testIds.Distinct())
{
/// how can I take step by step the name, age, informations for all test cases ?
}

我怎样才能做到这一点?

最佳答案

创建匿名(或引入自己的类)实例并在foreach 循环中使用它

var tests = xInformations.Descendants("test")
.Select(x =>
{
new
{
Id = x.Attribute("id")?.Value,
Name = x.Element("name").Value,
Age = x.Element("age").Value,
Info = x.Element("informations").Value
}
});

foreach(var test in tests)
{
// test.Id
// test.Name
// test.Age
// test.Info
}

或者如果 xml 文件的架构保持不变,您可以使用更清晰的代码和 XmlSerializer

[XmlType("tests")]
public class Tests
{
public List<Test> Tests { get; set; }
}

[XmlType("test")]
public class Test
{
[XmlAttribute("id")]
public int Id { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("age")]
public int Age { get; set; }
[XmlElement("informations")]
public string Info { get; set; }
}

var serializer = new XmlSerializer(typeof(Tests));
Tests tests = null;
using (var reader = new StreamReader(pathToXmlFile))
{
tests = (Tests)serializer.Deserialize(reader);
}

// use tests for your needs
foreach(var test in tests.Tests)
{
// test.Id
}

关于c# - XDocument 节点中的 Foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45502922/

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