首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在foreach循环中从XElement添加到列表

在foreach循环中,从XElement添加到列表是指将XElement对象中的数据添加到一个列表中。XElement是.NET Framework中用于处理XML数据的类。

XElement是XML元素的表示,它包含了元素的标签、属性和内容。在foreach循环中,可以遍历一个包含多个XElement对象的集合,然后将每个XElement对象中的数据提取出来,并添加到一个列表中。

以下是一个示例代码:

代码语言:txt
复制
using System;
using System.Collections.Generic;
using System.Xml.Linq;

public class Program
{
    public static void Main()
    {
        // 创建一个包含多个XElement对象的集合
        List<XElement> elements = new List<XElement>();
        elements.Add(new XElement("Person", new XAttribute("Id", 1), new XElement("Name", "John")));
        elements.Add(new XElement("Person", new XAttribute("Id", 2), new XElement("Name", "Jane")));
        elements.Add(new XElement("Person", new XAttribute("Id", 3), new XElement("Name", "Tom")));

        // 创建一个空列表,用于存储从XElement中提取的数据
        List<string> names = new List<string>();

        // 使用foreach循环遍历XElement集合,并将每个XElement中的Name元素的值添加到列表中
        foreach (XElement element in elements)
        {
            names.Add(element.Element("Name").Value);
        }

        // 打印列表中的数据
        foreach (string name in names)
        {
            Console.WriteLine(name);
        }
    }
}

在上述代码中,我们首先创建了一个包含多个XElement对象的集合。然后,我们创建了一个空列表用于存储从XElement中提取的数据。接下来,我们使用foreach循环遍历XElement集合,并通过element.Element("Name").Value语句提取每个XElement中的Name元素的值,并将其添加到列表中。最后,我们打印列表中的数据。

这个例子中的XElement对象表示了一个包含Person信息的XML元素,其中包含了一个Id属性和一个Name子元素。通过遍历XElement集合,并提取每个XElement中的Name元素的值,我们将John、Jane和Tom这三个名字添加到了列表中。

腾讯云相关产品和产品介绍链接地址:

  • 腾讯云云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 腾讯云云数据库 MySQL 版:https://cloud.tencent.com/product/cdb_mysql
  • 腾讯云对象存储(COS):https://cloud.tencent.com/product/cos
  • 腾讯云人工智能:https://cloud.tencent.com/product/ai
  • 腾讯云物联网平台:https://cloud.tencent.com/product/iotexplorer
  • 腾讯云移动开发:https://cloud.tencent.com/product/mobile
  • 腾讯云区块链服务:https://cloud.tencent.com/product/tbaas
  • 腾讯云元宇宙:https://cloud.tencent.com/product/tencentmetaverse
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券