我可以从XmlSchemaSet创建数据集吗

本文关键字:数据集 创建 XmlSchemaSet 我可以 | 更新日期: 2023-09-27 17:58:37

我从其他地方接收到一个XmlSchemaSet对象,是否可以使用它来构造一个使用它的DataSet

一些背景

XmlSchemaSet是使用自定义XmlResolver读取的,原始模式文件具有链接到要由自定义解析程序解析的其他文件的xs:include元素。我确认DataSet.ReadXmlSchema没有正确读取这些文件,即使我给它发送了一个带有自定义XmlReaderSettingsXmlReader。我认为这是因为XmlReader只解析DTD所需的uri,而xs:include引用则不解析。

可能的解决方案

当我深入研究DataSet.ReadXmlSchema的实现时,它似乎调用了XSDSchema.LoadSchema(schemaSet,dataSet)方法来完成这项工作。这就是我想要的。但不幸的是,XSDSchemainternal,除非我以某种方式破解它,否则无法访问。

那么,还有其他解决方案可以解决这个问题吗?

我可以从XmlSchemaSet创建数据集吗

下面的方法对我有效。它获取xmlSchemaSet的字符串表示,然后用StringReader读取它,这是readXmlSchema方法可以接受的。

public static class Utilities
{
    public static DataSet ToDataSet(this XmlSchemaSet xmlSchemaSet)
    {
        var schemaDataSet = new DataSet();
        string xsdSchema = xmlSchemaSet.GetString();
        schemaDataSet.ReadXmlSchema(new StringReader(xsdSchema));
        return schemaDataSet;
    }
    private static string GetString(this XmlSchemaSet xmlSchemaSet)
    {
        var settings = new XmlWriterSettings
                       {
                           Encoding = new UTF8Encoding(false, false),
                           Indent = true,
                           OmitXmlDeclaration = false
                       };
        string output;
        using (var textWriter = new StringWriterWithEncoding(Encoding.UTF8))
        {
            using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
            {
                foreach (XmlSchema s in xmlSchemaSet.Schemas())
                {
                    s.Write(xmlWriter);
                }
            }
            output = textWriter.ToString();
        }
        return output;
    }
}
public sealed class StringWriterWithEncoding : StringWriter
{
    private readonly Encoding _encoding;
    public StringWriterWithEncoding(Encoding encoding)
    {
        _encoding = encoding;
    }
    public override Encoding Encoding
    {
        get
        {
            return _encoding;
        }
    }
}

这是我的"黑客"解决方案,似乎是有效的:

private static Action<XmlSchemaSet, DataSet> GetLoadSchemaMethod()
{
    var type = (from aN in Assembly.GetExecutingAssembly().GetReferencedAssemblies()
        where aN.FullName.StartsWith("System.Data")
        let t = Assembly.Load(aN).GetType("System.Data.XSDSchema")
        where t != null
        select t).FirstOrDefault();
    var pschema = Expression.Parameter(typeof (XmlSchemaSet));
    var pdataset = Expression.Parameter(typeof (DataSet));
    var exp = Expression.Lambda<Action<XmlSchemaSet, DataSet>>(Expression.Call
        (Expression.New(type.GetConstructor(new Type[] {}), new Expression[] {}),
            type.GetMethod("LoadSchema", new[]
            {
                typeof (XmlSchemaSet), typeof (DataSet)
            }), new Expression[]
            {
                pschema, pdataset
            }), new[] {pschema, pdataset});
    return exp.Compile();
}

然而,我仍然不喜欢做黑客。