You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将结构多变的XML解析为List<string>?

解析无统一结构的XML为List

问题描述

我有加载到浏览器中的单客户XML数据,其结构存在10-15种无统一标准的模板:部分模板缺少元素、部分元素顺序不同、部分含额外信息,每个客户XML包含68-278个元素。需将此类XML解析为List<string>,其中每个元素值作为列表的一项(示例:List[0] = "Carl",List[1] = "Smith"等,数字也需转为字符串)。参考了相关方案,但因元素名称不固定,不知如何修改现有代码,请求提供可行的C#代码。现有代码如下:

using System;
using System.Linq;
using System.Xml.Linq;

public class Test
{
    static void Main()
    {

     string _url = _UrlMaker.GetUrl(); //method which extracts URL with the XML data
     WebClient client = new WebClient(); 
     var xml = client.DownloadString(_url); //this should load the XML?

        XDocument doc = XDocument.Parse(xml);

        var list = doc.Root.Elements(YXYXYXXYX)
                           .Select(element => element.Value)
                           .ToList();                
    }
}

解决方案代码

基于WebClient的实现(兼容.NET Framework)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Xml.Linq;

public class Test
{
    static void Main()
    {
        string _url = _UrlMaker.GetUrl();
        
        // 使用using确保资源自动释放
        using (WebClient client = new WebClient())
        {
            string xml = client.DownloadString(_url);
            XDocument doc = XDocument.Parse(xml);

            // 方案1:仅提取根节点的直接子元素值(忽略嵌套元素)
            List<string> directChildValues = doc.Root.Elements()
                                                  .Select(el => el.Value.Trim())
                                                  .ToList();

            // 方案2:提取所有层级的元素值(包含嵌套子元素,适配复杂非标准模板)
            List<string> allElementValues = doc.Descendants()
                                              .Select(el => el.Value.Trim())
                                              .ToList();

            // 可选:过滤空值或纯空白字符串
            List<string> filteredValues = allElementValues.Where(val => !string.IsNullOrWhiteSpace(val)).ToList();
        }
    }
}

基于HttpClient的实现(推荐.NET Core/.NET 5+)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Xml.Linq;
using System.Threading.Tasks;

public class Test
{
    static async Task Main()
    {
        string _url = _UrlMaker.GetUrl();
        
        using (HttpClient client = new HttpClient())
        {
            string xml = await client.GetStringAsync(_url);
            XDocument doc = XDocument.Parse(xml);

            // 提取所有层级非空的元素值
            List<string> resultList = doc.Descendants()
                                        .Select(el => el.Value.Trim())
                                        .Where(val => !string.IsNullOrWhiteSpace(val))
                                        .ToList();
        }
    }
}

关键说明

  • 移除固定元素名称硬编码:Elements()无参数时获取根节点下所有直接子元素;Descendants()遍历XML所有层级元素,适配嵌套结构的非标准模板。
  • Trim()清理元素值前后空白,避免无效空内容。
  • 空值过滤逻辑可按需启用,剔除无意义的空白字符串。
  • WebClient在.NET Core及更高版本中已过时,官方推荐使用HttpClient实现异步网络请求。

内容的提问来源于stack exchange,提问作者Matěj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 08:44:55