How can I resolve the schemaLocation attribute of an .XSD when all of my .XSD's are stored as resources?

后端 未结 1 1150
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 13:26

I am working on a project where I need to generate XML files based on nested XSD\'s. e.g. ORDER has a reference to PERSON, PERSON has a reference to ADDRESS, etc.

I

1条回答
  •  自闭症患者
    2020-12-06 13:55

    To get rid of the error, change type="Addresses" to name="Addresses" in your PERSON.xsd file.

    It is better to go with the code below to get schemas compiled. The important things are to make sure you establish a base uri (since you're reading from a stream), to use an XmlSchemaSet instead, and a custom resolver (to read files as embedded resources).

    using System;
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Xml.Schema;
    
    namespace ConsoleApplication3
    {
        class Program
        {
            class XmlResolver : XmlUrlResolver
            {
                internal const string BaseUri = "schema://";
    
                public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
                {
                    if (absoluteUri.Scheme == "schema")
                    {
                        switch (absoluteUri.LocalPath)
                        {
                            case "/ADDRESS.xsd":
                                return new MemoryStream(Encoding.UTF8.GetBytes(Resource.ADDRESS));
                            case "/PERSON.xsd":
                                return new MemoryStream(Encoding.UTF8.GetBytes(Resource.PERSON));
                        }
                    }
                    return base.GetEntity(absoluteUri, role, ofObjectToReturn);
                }
            }
    
            static void Main(string[] args)
            {
                using (XmlReader reader = XmlReader.Create(new StringReader(Resource.PERSON), new XmlReaderSettings(), XmlResolver.BaseUri))
                {
                    XmlSchemaSet xset = RetrieveSchemaSet(reader);
                    Console.WriteLine(xset.IsCompiled);
                }
            }
    
            private static XmlSchemaSet RetrieveSchemaSet(XmlReader reader)
            {
                XmlSchemaSet xset = new XmlSchemaSet() { XmlResolver = new XmlResolver() };
                xset.Add(XmlSchema.Read(reader, null));
                xset.Compile();
                return xset;
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题