【问题标题】:Foreach in XDocument nodesXDocument 节点中的 Foreach
【发布时间】:2023-03-12 14:34:01
【问题描述】:
<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 ?
}

我怎样才能做到这一点?

【问题讨论】:

  • 我没有找到使用 XDocument
  • 啊,对不起:)
  • 无论如何,您可以找到很多示例:herehere 等等。您尝试过其中任何一个吗?
  • @FlorinM。您在下图中看到了它从属性中获取值的图像。我被检查了你的确切例外是什么。

标签: c# asp.net


【解决方案1】:

创建匿名(或引入自己的类)实例并在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
}

【讨论】:

  • Id = x.Attribute("id").Value -> 不起作用...我试过了,我无法获得测试ID
  • @FlorinM.,你所说的“不工作”是什么意思,你有例外吗?
【解决方案2】:
string path = @"D:\1.txt";
  XDocument _doc = XDocument.Load(path);

  List<XElement> testIds = new List<XElement>();

  testIds = _doc.Descendants("test").ToList();


  foreach (XElement extId in testIds.Distinct())
  {
     // get element values
        string id = extId.Attribute("id").Value;
        string name = extId.Element("name").Value;
        string age = extId.Element("age").Value;
        string info = extId.Element("informations").Value;
        Console.WriteLine(name + ", " + " " + age + ", " + info);
  }

字符串 id = extId.Attribute("id").Value;

Attribute方法用于获取属性值内节点的值。

我已检查数据是否正确地从属性中获取。

【讨论】:

  • 如果“id”属性缺失,exId.Attrbute("id").Value 行会抛出NullReferenceException,因为Element.Attribute 方法会返回null
  • @Fabio 在给定的 xml 中所有具有 Id 属性的元素。所以,我不检查 null。感谢您的评论
【解决方案3】:

这是你可以做到的方式

        // path to file
        string path = @"C:\t\1.txt";
        XDocument _doc = XDocument.Load(path);

        List<XElement> testIds = new List<XElement>();
        // get all test elements
        testIds = _doc.Descendants("test").ToList();

        // loop true test elements
        foreach (XElement extId in testIds.Distinct())
        {
            // get element values

            string id = extId.Attribute("id").Value;
            string name = extId.Element("name").Value;
            string age = extId.Element("age").Value;
            string info = extId.Element("informations").Value;
            Console.WriteLine(id+ "," + name + ", " + " " + age + ", " + info);
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多