且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 xsd.exe 生成 C# 类,如何指定现有类型?

更新时间:2022-06-06 01:59:44

我不确定这是否是***的方法,但我通过实施 SchemaImporterExtension:

I'm not sure if this is the best way, but I managed to do something by implementing SchemaImporterExtension:

namespace SchemaImport
{
    public class ADODBSchemaImporterExtension : SchemaImporterExtension
    {

        public override CodeExpression ImportDefaultValue(string value, string type)
        {
            return new CodeTypeReferenceExpression(type);
        }

        public override string ImportSchemaType(XmlSchemaType type,
            XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer,
            CodeCompileUnit compileUnit, CodeNamespace codeNamespace,
            CodeGenerationOptions options, CodeDomProvider codeGenerator)
        {
        return null;
        }

        public override string ImportSchemaType(string name, 
            string ns, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, 
            CodeCompileUnit compileUnit, CodeNamespace mainNamespace, 
            CodeGenerationOptions options, CodeDomProvider codeProvider)
        {
            if (name.StartsWith("ADODB."))
            {
                compileUnit.ReferencedAssemblies.Add("adodb.dll");
                mainNamespace.Imports.Add(new CodeNamespaceImport("ADODB"));
                return name.Substring(name.IndexOf(".") + 1);
            }
            return null;
        }
    }
}

连同将 ADODB.Recordset 定义为 xsd:complexType:

<xs:element name="Table">
    <xs:complexType>
        <xs:all>
            <!-- ...snip... -->
            <xs:element name="CellValues" type="ADODB.RecordSet"/>
        </xs:all>
    </xs:complexType>
</xs:element>
<xs:complexType name="ADODB.Recordset"/>

然后我不得不将这个类添加到 machine.config:

I then had to add this class to machine.config:

<system.xml.serialization>
    <schemaImporterExtensions> 
        <add type="SchemaImport.ADODBSchemaImporterExtension, SchemaImport, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cd583032ee337c41" /> 
    </schemaImporterExtensions>
</system.xml.serialization>

并将参数文件中的程序集(/p:parameters.xml 开关)指定为 xsd.exe:

and specify the assembly in a parameter file (the /p:parameters.xml switch) to xsd.exe:

<?xml version="1.0" encoding="UTF-8"?>
<xsd xmlns='http://microsoft.com/dotnet/tools/xsd/'>
    <generateClasses language='c#' namespace='TableDocument'>
        <schemaImporterExtensions>
            <type>SchemaImport.ADODBSchemaImporterExtension, SchemaImport, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cd583032ee337c41</type>
        </schemaImporterExtensions>
    </generateClasses>
</xsd>

我最终得到了一个带有适当 Table 类的 .cs 文件,位于 TableDocument 命名空间中,该命名空间以 ADODB 作为参考和 using 语句.

I ended up with a .cs file with the appropriate Table class, in the TableDocument namespace that had the ADODB as a reference and using statement.