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

将XML读取至DataSet:按SO方案转换生成3个数据表的技术问询

将指定XML转换为DataSet的实现方案

刚好处理过类似的XML转DataSet场景,直接给你上可运行的代码和详细说明:

实现代码(C#)

using System.Data;
using System.IO;
using System.Xml;

public DataSet ConvertXmlToDataSet(string xmlContent)
{
    var dataSet = new DataSet();
    // 使用StringReader和XmlReader读取XML内容
    using var stringReader = new StringReader(xmlContent);
    using var xmlReader = XmlReader.Create(stringReader);
    
    dataSet.ReadXml(xmlReader);
    return dataSet;
}

// 调用示例
var xmlContent = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<data>
  <child1>
    <to>alice@mail.com</to>
    <from>bob@mail.com</from>
    <name>alice alicia</name>
  </child1>
  <child2>
    <file>
      <size>123</size>
      <content>lorem ipsum</content>
    </file>
  </child2>
</data>";

DataSet convertedDataSet = ConvertXmlToDataSet(xmlContent);

生成的DataSet数据表结构说明

运行后DataSet会自动生成3张数据表,对应XML的层级结构:

  • child1:包含to、from、name三列,存储节点下的所有字段值,仅有1行数据(就是你提供的alice邮箱、bob邮箱和alice的全名)
  • child2:作为节点的父表,会自动生成一个主键列(比如child2_Id),用来关联子表,同样仅有1行数据
  • file:包含size、content两列,外加一个外键列(比如child2_Id)和child2表建立关联,存储节点下的大小和内容数据,也是1行数据

原理是DataSet的ReadXml方法会自动解析XML的嵌套层级,推断表结构和表间关系,非常适合这种结构化XML的转换需求。

内容的提问来源于stack exchange,提问作者bentz123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:15:49