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

如何从多个XML文件自动生成C#类

批量将XML转换为类的解决方案

针对你需要批量处理128个XML文件的需求,以下是两种替代手动操作的高效方法,原理和VS的「Paste XML as classes」一致:

方法一:使用xsd.exe工具(VS自带)

VS的XML转类功能底层依赖xsd.exe工具,你可以通过PowerShell脚本批量调用它:

  1. 将所有XML文件集中到一个单独的文件夹,比如D:\XmlFiles。
  2. 打开Visual Studio开发者命令提示符(确保能直接调用xsd.exe)。
  3. 执行以下PowerShell脚本:
    # 替换为你的XML文件夹、临时XSD输出文件夹、最终类文件输出文件夹
    $xmlDir = "D:\XmlFiles"
    $xsdDir = "D:\TempXsdFiles"
    $classDir = "D:\GeneratedClasses"
    
    # 创建输出文件夹(如果不存在)
    if (-not (Test-Path $xsdDir)) { New-Item -ItemType Directory -Path $xsdDir | Out-Null }
    if (-not (Test-Path $classDir)) { New-Item -ItemType Directory -Path $classDir | Out-Null }
    
    # 遍历XML生成XSD文件
    Get-ChildItem -Path $xmlDir -Filter *.xml | ForEach-Object {
        xsd.exe $_.FullName /outputdir:$xsdDir
    }
    
    # 遍历XSD生成C#类文件
    Get-ChildItem -Path $xsdDir -Filter *.xsd | ForEach-Object {
        # 可添加/namespace:Your.Namespace指定命名空间,/language:VB生成VB类
        xsd.exe $_.FullName /classes /language:CS /outputdir:$classDir
    }
    

方法二:编写C#控制台程序自定义生成

如果需要更灵活的控制(比如统一命名空间、自定义类名规则),可以写一个简单的控制台程序:

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.CSharp;

class BatchXmlToClass
{
    static void Main(string[] args)
    {
        // 替换为你的实际路径和命名空间
        string xmlFolder = @"D:\XmlFiles";
        string outputFolder = @"D:\GeneratedClasses";
        string targetNamespace = "Your.Project.Namespace";

        if (!Directory.Exists(outputFolder))
            Directory.CreateDirectory(outputFolder);

        foreach (var xmlPath in Directory.GetFiles(xmlFolder, "*.xml"))
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlPath);

                XmlSchemaSet schemaSet = new XmlSchemaSet();
                schemaSet.Add("", XmlReader.Create(new StringReader(xmlDoc.InnerXml)));

                CodeNamespace codeNs = new CodeNamespace(targetNamespace);
                XmlSchemaImporter importer = new XmlSchemaImporter(schemaSet);
                XmlTypeMapping typeMapping = importer.ImportTypeMapping(new XmlQualifiedName("", ""));

                using (CSharpCodeProvider codeProvider = new CSharpCodeProvider())
                {
                    CodeGeneratorOptions options = new CodeGeneratorOptions
                    {
                        BracingStyle = "C",
                        IndentString = "    ",
                        BlankLinesBetweenMembers = true
                    };

                    string className = Path.GetFileNameWithoutExtension(xmlPath);
                    string outputPath = Path.Combine(outputFolder, $"{className}.cs");

                    using (StreamWriter writer = new StreamWriter(outputPath))
                    {
                        codeProvider.GenerateCodeFromType(typeMapping, writer, options);
                    }

                    Console.WriteLine($"已生成类文件:{outputPath}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理文件 {xmlPath} 失败:{ex.Message}");
            }
        }

        Console.WriteLine("批量转换完成,按任意键退出...");
        Console.ReadKey();
    }
}

注意事项

  • 如果XML文件存在相同结构,可合并对应的XSD文件后再生成类,减少重复代码。
  • 部分复杂XML可能需要手动调整生成的类(比如处理数组、可选元素),但大部分场景下自动生成的代码可直接使用。

内容的提问来源于stack exchange,提问作者Paweł Lisy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 23:19:01