当前位置: 首页>>代码示例>>C#>>正文


C# XmlSchema.Write方法代码示例

本文整理汇总了C#中System.Xml.Schema.XmlSchema.Write方法的典型用法代码示例。如果您正苦于以下问题:C# XmlSchema.Write方法的具体用法?C# XmlSchema.Write怎么用?C# XmlSchema.Write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Xml.Schema.XmlSchema的用法示例。


在下文中一共展示了XmlSchema.Write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        public static void Main(string[] args)
        {
            XmlSchemaType rootType = CSON.ToSchemaType (typeof(CSONThing));
            XmlSchemaElement rootElement = new XmlSchemaElement ();
            rootElement.Name = typeof(CSONThing).Name;
            rootElement.SchemaType = rootType;
            XmlSchema typeSchema = new XmlSchema ();
            typeSchema.Items.Add (rootElement);
            typeSchema.TargetNamespace = typeof(CSONThing).Name + "Data";

            FileStream file = new FileStream("../../new.xsd", FileMode.Create, FileAccess.ReadWrite);
            XmlTextWriter xwriter = new XmlTextWriter(file, new UTF8Encoding());
            xwriter.Formatting = Formatting.Indented;

            typeSchema.Write (xwriter);
        }
开发者ID:mattmanj17,项目名称:Kvothe,代码行数:16,代码来源:Program.cs

示例2: ConvertSchemaToString

        private static string ConvertSchemaToString(XmlSchema schema)
        {
            using (var stream = new MemoryStream())
            {
                schema.Write(stream);

                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);

                var reader = new StreamReader(stream, Encoding.UTF8);
                string schemaXml = reader.ReadToEnd();

                if (!String.IsNullOrWhiteSpace(schemaXml))
                {
                    return FormatXml(schemaXml);
                }
            }

            return null;
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:20,代码来源:XmlSchemasExtensions.cs

示例3: XsdClassGenerator

        /// <summary>
        /// Constructor:
        /// - initialize the schema
        /// - compile the schema
        /// - set some defaults
        /// </summary>
        /// <param name="schema"></param>
        public XsdClassGenerator(XmlSchema schema)
        {
            m_schema = schema;
            if (m_schema == null)
                throw new ArgumentNullException("schema", "Xml Schema cannot be null");

            #region save the schema to an XmlDocument
            StringWriter sw = new StringWriter();
            m_schema.Write(sw);
            this.SourceDocument.LoadXml(sw.ToString());
            #endregion

            Utility.CompileSchema(schema);

            PreProcessSchemas();

            CompilerParameters.GenerateExecutable = false;
            CompilerParameters.GenerateInMemory = true;

            AddDefaultCodeModifiers();

        }
开发者ID:nujmail,项目名称:xsd-to-classes,代码行数:29,代码来源:XsdClassGenerator.cs

示例4: GenerateSchemas

        static List<string> GenerateSchemas(string inputFolder, string outputFolder)
        {
            var schemaFiles = Directory.GetFiles(inputFolder);

            List<string> filesForCleanUp = new List<string>();
            Dictionary<string, XmlSchema> namespaceToSchema = new Dictionary<string, XmlSchema>();
            Dictionary<string, string> namespaceToFile = new Dictionary<string, string>();

            foreach (string schemaFile in schemaFiles)
            {
                try
                {
                    XmlSchema xmlSchema = GetSchemaFromFile(schemaFile);
                    FileInfo file = new FileInfo(schemaFile);

                    namespaceToSchema.Add(xmlSchema.TargetNamespace, xmlSchema);
                    namespaceToFile.Add(xmlSchema.TargetNamespace, file.Name);
                }
                catch (Exception ex)
                {
                    // in order to catch exception message
                    throw ex;
                }
            }

            XmlSchema allSchema = new XmlSchema();
            allSchema.ElementFormDefault = XmlSchemaForm.Qualified;
            HashSet<string> allSchemaElementNames = new HashSet<string>();

            foreach (var kvp in namespaceToSchema)
            {
                string schemaNamespace = kvp.Key;
                XmlSchema xmlSchema = kvp.Value;
                string schemaLocation = namespaceToFile[schemaNamespace];

                foreach (XmlSchemaComplexType complexType in xmlSchema.Items.OfType<XmlSchemaComplexType>())
                {
                    string typeName = complexType.Name;
                    string elementName = typeName;

                    int i = 0;
                    while (allSchemaElementNames.Contains(elementName))
                    {
                        elementName = string.Format("{0}{1}", typeName, i++);
                    }

                    allSchemaElementNames.Add(elementName);

                    allSchema.Items.Add(new XmlSchemaElement() { SchemaTypeName = new XmlQualifiedName(complexType.Name, schemaNamespace), Name = elementName });
                }
                allSchema.Includes.Add(new XmlSchemaImport { Namespace = schemaNamespace, SchemaLocation = schemaLocation });

                foreach (XmlSchemaImport include in xmlSchema.Includes)
                {
                    if (namespaceToSchema.ContainsKey(include.Namespace))
                    {
                        include.SchemaLocation = namespaceToFile[include.Namespace];
                    }
                }

                string schemaFile = Path.Combine(outputFolder, schemaLocation);
                filesForCleanUp.Add(schemaFile);
                using (FileStream fs = new FileStream(schemaFile, FileMode.Create))
                {
                    xmlSchema.Write(fs);
                }
            }

            string allSchemaFile = Path.Combine(outputFolder, "All.xsd");
            filesForCleanUp.Add(allSchemaFile);
            using (FileStream fs = new FileStream(allSchemaFile, FileMode.Create))
            {
                allSchema.Write(fs);
            }

            return filesForCleanUp;
        }
开发者ID:MartinBG,项目名称:Gva,代码行数:77,代码来源:Program.cs

示例5: Main

        /// <summary>
        /// Entry point
        /// </summary>
        /// <param name="args">The args.</param>
        private static void Main(string[] args)
        {
            Assemblies = new List<string>();
            Types = new List<string>();
            Dir = new List<string>();
            RootList = new List<string>();

            OptionSet p = null;
            p = new OptionSet().Add("v", "Verbose mode", v => VerboseMode = true).Add(
                "f|force", "Overwrite schema if exists", str => OverwriteMode = true).Add(
                    "a=|assembly=",
                    "Generate schemas for one or more types in this assembly",
                    str => Assemblies.Add(str)).Add(
                        "d=|directory=", "Search for dependencies in this directory", str => Dir.Add(str)).Add(
                            "o=|output=",
                            "Generate schema in this directory. By default, schemas are generated in the same directory as the assembly",
                            str => OutDir = str).Add(
                                "r=|root=", "Emit element node at schema root for this type", str => RootList.Add(str))
                // ReSharper disable AccessToModifiedClosure
                .Add("h|help", "This message", str => Help(p))
                // ReSharper restore AccessToModifiedClosure
                .Add("t=|type=", "TBD: Emit only specified types", str => Types.Add(str));

            p.Parse(args);

            if (Assemblies.Count == 0)
            {
                Help(p);
                return;
            }

            foreach (var name in Assemblies)
            {
                Console.WriteLine("Processing: " + name);

                try
                {
                    var asHelper = new AssemblyHelper(VerboseMode) { AssemblyName = name };

                    asHelper.SearchDirs.AddRange(Dir);
                    asHelper.SearchTypes.AddRange(Types);

                    if (VerboseMode)
                    {
                        Console.WriteLine("Types in assembly");
                        foreach (var t in asHelper.Types)
                        {
                            Console.WriteLine("\t{0}", t);
                        }
                    }

                    // look for classes with datacontract attribute
                    var contractList = asHelper.GetTypesWithAttribute(typeof(DataContractAttribute));
                    if (VerboseMode)
                    {
                        Console.WriteLine("Types with [DataContract] attribute");
                        foreach (var t in contractList)
                        {
                            Console.WriteLine("\t{0}", t);
                        }
                    }

                    var customTypeList = new List<XmlQualifiedName>();
                    var emittedTypeList = new List<string>();
                    var set = new XmlSchemaSet();
                    set.ValidationEventHandler += set_ValidationEventHandler;
                    foreach (var t in contractList)
                    {
                        var si = t.GetSchema();
                        set.Add(si.Schema);
                        emittedTypeList.Add(t.Name);
                        customTypeList.AddRange(si.CustomTypes);
                    }

                    // iterate through custom list until all of them are emitted
                    while (customTypeList.Count > 0)
                    {
                        var customList = new List<XmlQualifiedName>();
                        foreach (var c in customTypeList)
                        {
                            if (emittedTypeList.Contains(c.Name))
                            {
                                continue;
                            }

                            var name1 = c.Name;
                            var isList = false;

                            if (name1.StartsWith("ArrayOf"))
                            {
                                name1 = name1.Substring(7);
                                isList = true;
                            }

                            var t1 = contractList.FirstOrDefault(x => x.Name == name1);
                            if (t1 == null)
//.........这里部分代码省略.........
开发者ID:destevil,项目名称:CSharp2Xsd,代码行数:101,代码来源:Program.cs

示例6: TestWriteNamespaces

		public void TestWriteNamespaces ()
		{
			XmlDocument doc = new XmlDocument ();
			XmlSchema xs;
			StringWriter sw;
			XmlTextWriter xw;

			// empty
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			Assert.AreEqual ("<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml, "#1");

			// TargetNamespace
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			xs.TargetNamespace = "urn:foo";
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			Assert.AreEqual ("<xs:schema xmlns:tns=\"urn:foo\" targetNamespace=\"urn:foo\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml, "#2");

			// Zero-length TargetNamespace
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			xs.TargetNamespace = string.Empty;
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			Assert.AreEqual ("<xs:schema targetNamespace=\"\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml, "#2b");

			// XmlSerializerNamespaces
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			xs.Namespaces.Add ("hoge", "urn:hoge");
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			// commenting out. .NET 2.0 outputs xs:schema instead of schema, that also makes sense.
			// Assert.AreEqual ("<schema xmlns:hoge=\"urn:hoge\" xmlns=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml, "#3");

			// TargetNamespace + XmlSerializerNamespaces
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			xs.TargetNamespace = "urn:foo";
			xs.Namespaces.Add ("hoge", "urn:hoge");
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			// commenting out. .NET 2.0 outputs xs:schema instead of schema, that also makes sense.
			// Assert.AreEqual ("<schema xmlns:hoge=\"urn:hoge\" targetNamespace=\"urn:foo\" xmlns=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml, "#4");

			// Add XmlSchema.Namespace to XmlSerializerNamespaces
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			xs.Namespaces.Add ("a", XmlSchema.Namespace);
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			Assert.AreEqual ("<a:schema xmlns:a=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml, "#5");

			// UnhandledAttributes + XmlSerializerNamespaces
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			XmlAttribute attr = doc.CreateAttribute ("hoge");
			xs.UnhandledAttributes = new XmlAttribute [] {attr};
			xs.Namespaces.Add ("hoge", "urn:hoge");
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			// commenting out. .NET 2.0 outputs xs:schema instead of schema, that also makes sense.
			// Assert.AreEqual ("<schema xmlns:hoge=\"urn:hoge\" hoge=\"\" xmlns=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml, "#6");

			// Adding xmlns to UnhandledAttributes -> no output
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			attr = doc.CreateAttribute ("xmlns");
			attr.Value = "urn:foo";
			xs.UnhandledAttributes = new XmlAttribute [] {attr};
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			Assert.AreEqual ("<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml, "#7");
		}
开发者ID:Profit0004,项目名称:mono,代码行数:86,代码来源:XmlSchemaTests.cs

示例7: GetBuiltinSimpleTypeWorksAsEcpected

        public void GetBuiltinSimpleTypeWorksAsEcpected()
        {
            Initialize();
            string xml = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + "\r\n" +
 "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + "\r\n" +
 "  <xs:simpleType>" + "\r\n" +
 "    <xs:restriction base=\"xs:anySimpleType\" />" + "\r\n" +
 "  </xs:simpleType>" + "\r\n" +
 "</xs:schema>";
            XmlSchema schema = new XmlSchema();
            XmlSchemaSimpleType stringType = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String);
            schema.Items.Add(stringType);
            StringWriter sw = new StringWriter();
            schema.Write(sw);
            CError.Compare(sw.ToString(), xml, "Mismatch");
            return;
        }
开发者ID:dotnet,项目名称:corefx,代码行数:17,代码来源:TC_SchemaSet_Misc.cs

示例8: GetSchema

        /// <summary>
        /// Returns the schema for the specified type (returns the entire schema if null).
        /// </summary>
        public override string GetSchema(string typeName)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            
            settings.Encoding    = Encoding.UTF8;
            settings.Indent      = true;
            settings.IndentChars = "    ";

            MemoryStream ostrm = new MemoryStream();
            XmlWriter writer = XmlWriter.Create(ostrm, settings);
            
            try
            {
                if (typeName == null || m_schema.Elements.Values.Count == 0)
                {
                    m_schema.Write(writer);
                }
                else
                {
                    foreach (XmlSchemaObject current in m_schema.Elements.Values)
                    {       
                        XmlSchemaElement element = current as XmlSchemaElement;

                        if (element != null)
                        {
                            if (element.Name == typeName)
                            {                                
                                XmlSchema schema = new XmlSchema();
                                schema.Items.Add(element.ElementSchemaType);
                                schema.Items.Add(element);
                                schema.Write(writer);
                                break;
                            }
                        }
                    }
                }
            }
            finally
            {
                writer.Close();
            }

            return new UTF8Encoding().GetString(ostrm.ToArray());
        } 
开发者ID:yuriik83,项目名称:UA-.NET,代码行数:47,代码来源:XmlSchemaValidator.cs

示例9: XmlSchemaToXElement

        private static XElement XmlSchemaToXElement(XmlSchema schema)
        {
            XmlWriterSettings settings = new XmlWriterSettings
            {
                CloseOutput = false,
                Indent = true,
            };

            XDocument schemaDocument = new XDocument();

            using (XmlWriter writer = XmlWriter.Create(schemaDocument.CreateWriter(), settings))
            {
                schema.Write(writer);
            }
            return schemaDocument.Root;
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:16,代码来源:HelpHtmlBuilder.cs

示例10: SchemaToString

 /// <summary>
 ///     Converts the Schema object into a string
 /// </summary>
 private string SchemaToString(XmlSchema schema)
 {
     using (var memoryStream = new MemoryStream())
     {
         schema.Write(memoryStream);
         memoryStream.Position = 0;
         var reader = new StreamReader(memoryStream);
         return reader.ReadToEnd();
     }
 }
开发者ID:flcdrg,项目名称:XSDExtractor,代码行数:13,代码来源:EdgeCases.cs

示例11: TestWriteNamespaces

		public void TestWriteNamespaces ()
		{
			XmlDocument doc = new XmlDocument ();
			XmlSchema xs;
			StringWriter sw;
			XmlTextWriter xw;

			// empty
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			AssertEquals ("#1", "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml);

			// TargetNamespace
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			xs.TargetNamespace = "urn:foo";
			xs.Write (xw);
			Console.WriteLine ("#2", "<xs:schema xmlns:tns=\"urn:foo\" targetNamespace=\"urn:foo\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml);

			// XmlSerializerNamespaces
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			xs.Namespaces.Add ("hoge", "urn:hoge");
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			AssertEquals ("#3", "<schema xmlns:hoge=\"urn:hoge\" xmlns=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml);

			// TargetNamespace + XmlSerializerNamespaces
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			xs.TargetNamespace = "urn:foo";
			xs.Namespaces.Add ("hoge", "urn:hoge");
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			AssertEquals ("#4", "<schema xmlns:hoge=\"urn:hoge\" targetNamespace=\"urn:foo\" xmlns=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml);

			// Add XmlSchema.Namespace to XmlSerializerNamespaces
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			xs.Namespaces.Add ("a", XmlSchema.Namespace);
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			AssertEquals ("#5", "<a:schema xmlns:a=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml);

			// UnhandledAttributes + XmlSerializerNamespaces
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			XmlAttribute attr = doc.CreateAttribute ("hoge");
			xs.UnhandledAttributes = new XmlAttribute [] {attr};
			xs.Namespaces.Add ("hoge", "urn:hoge");
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			AssertEquals ("#6", "<schema xmlns:hoge=\"urn:hoge\" hoge=\"\" xmlns=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml);

			// Adding xmlns to UnhandledAttributes -> no output
			xs = new XmlSchema ();
			sw = new StringWriter ();
			xw = new XmlTextWriter (sw);
			attr = doc.CreateAttribute ("xmlns");
			attr.Value = "urn:foo";
			xs.UnhandledAttributes = new XmlAttribute [] {attr};
			xs.Write (xw);
			doc.LoadXml (sw.ToString ());
			AssertEquals ("#7", "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" />", doc.DocumentElement.OuterXml);
		}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:73,代码来源:XmlSchemaTests.cs

示例12: Main

        //[STAThread]
        //[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
        static void Main(string[] args)
        {
            #region "testing xml"

            XmlDocument doc = new XmlDocument();
            using (XmlWriter xw = doc.CreateNavigator().AppendChild())
            {

                //MemoryStream ms = new MemoryStream();
                //XPathDocument xpath = new XPathDocument(ms);
                //XPathNavigator xpathnav = xpath.CreateNavigator();
                //XmlWriter xw = xpathnav.AppendChild();

                xw.WriteStartDocument();

                xw.WriteStartElement("Page");

                xw.WriteStartElement("Line");
                xw.WriteStartElement("Word");
                xw.WriteString("first line.");
                xw.WriteEndElement();
                xw.WriteEndElement();

                xw.WriteStartElement("Line");
                xw.WriteStartElement("Word");
                xw.WriteString("A SECOND WORD!!");
                xw.WriteEndElement();
                xw.WriteEndElement();

                xw.WriteEndElement(); //page

                xw.WriteEndDocument();

            }

            StringWriter ms = new StringWriter();
            XmlWriterSettings setting = new XmlWriterSettings
            {
                ConformanceLevel = ConformanceLevel.Auto
            };
            XmlWriter newXW = XmlWriter.Create(ms);

            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load("test.xslt");

            XmlNode root = doc.SelectSingleNode("/*");
            XPathNavigator xpath = root.CreateNavigator();

            //xslt.Transform(xpath, newXW);
            xslt.Transform(doc, null, ms);

            Console.WriteLine(ms.ToString());

            Environment.Exit(0);

            #endregion

            #region "testing Vector"
            //Vector v1 = new Vector(1f, 1f, 1f);
            //Vector v2 = new Vector(3f, 2f, 1f);
            //Vector result = v2.Subtract(v1);

            //Console.WriteLine(result[0]);
            //Console.WriteLine(result[1]);
            //Console.WriteLine(result[2]);
            //Console.WriteLine(Math.Atan2(1d, 1d)*180/Math.PI);

            //Environment.Exit(0);
            #endregion

            #region "testing data structures"
            //Stack<int> a = new Stack<int>();
            //a.Push(2);
            //a.Push(4);
            //a.Push(6);
            //a.Push(8);
            //a.Pop();
            //a.Push(3);
            //a.Pop();
            //a.Push(4);
            //a.Push(6);
            //a.Push(7);
            //a.Pop();
            //a.Pop();
            //a.Pop();
            //Console.WriteLine(a.Pop());
            //Environment.Exit(0);
            #endregion

            #region
            //testing merging tiff
            //List<string> lstImages = new List<string>();
            //lstImages.Add(@"C:\Users\janetxue\Downloads\Migration\testing\Corrupted PDF testing\100110.1");
            //lstImages.Add(@"C:\Users\janetxue\Downloads\Migration\testing\Corrupted PDF testing\100110.2");
            //string strDestinationFileName = @"C:\Users\janetxue\Downloads\Migration\testing\Corrupted PDF testing\merged.tif";

            //ImageCodecInfo codec = null;

//.........这里部分代码省略.........
开发者ID:xchgdzq233,项目名称:testing,代码行数:101,代码来源:Program.cs

示例13: LoadSchemaFromFile

        /// <summary>
        /// Loads the schema from file.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <returns>The xsd file as a formatted string</returns>
        /// <exception cref="System.Exception">
        /// Bad File Extension
        /// or
        /// File Doesn't Exist
        /// or
        /// </exception>
        public string LoadSchemaFromFile(string filePath)
        {
            mWarningsList.Clear();
            // check that it's an xml file
            if (Path.GetExtension(filePath) != ".xsd")
            {
                throw new Exception("Bad File Extension");
            }
            // check that the file exists
            if (!File.Exists(filePath))
            {
                throw new Exception("File Doesn't Exist");
            }

            string xsdContents = "";

            try
            {
                XmlTextReader reader = new XmlTextReader(filePath);
                mSchema = XmlSchema.Read(reader, ValidationCallback);

                MemoryStream memStream = new MemoryStream();
                XmlTextWriter writer = new XmlTextWriter(memStream, Encoding.Unicode);
                writer.Formatting = Formatting.Indented;
                mSchema.Write(writer);
                writer.Flush();
                memStream.Flush();
                memStream.Position = 0;
                // read the MemoryStream contents to a StreamReader
                StreamReader streamReader = new StreamReader(memStream);

                // get the formatted text from the stream reader
                xsdContents = streamReader.ReadToEnd();
                mbSchemaIsLoaded = true;
            }
            catch (System.Exception ex)
            {
                string exString = "Loading Error: " + ex.Message;
                throw new Exception(exString);
            }

            return xsdContents;
        }
开发者ID:JamesCMLucas,项目名称:XMLConfigurationEditor,代码行数:54,代码来源:cXMLHandler.cs

示例14: SchemaToString

 private string SchemaToString(XmlSchema schema)
 {
     var sw = new StringWriter();
     schema.Write(sw);
     return sw.ToString();
 }
开发者ID:flcdrg,项目名称:XSDExtractor,代码行数:6,代码来源:CollectionTests.cs

示例15: PrintSchema

        static void PrintSchema()
        {
            XmlSchema finalSchema = new XmlSchema();

            //add namespace
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
            String defaultNamespace = @"http://www.w3.org/2001/XMLSchema";
            nsmgr.AddNamespace("xsi", @"http://www.w3.org/2001/XMLSchema-instance");
            nsmgr.AddNamespace("ditaarch", @"http://dita.oasis-open.org/architecture/2005/");

            //root element
            XmlSchemaElement rootSchemaEl = new XmlSchemaElement();
            rootSchemaEl.Name = resultRule[0].name;
            rootSchemaEl.SchemaTypeName = new XmlQualifiedName(rootSchemaEl.Name);
            finalSchema.Items.Add(rootSchemaEl);

            //all types
            foreach (NodeClass currentNode in resultRule)
            {
                //simple type
                if (currentNode.childNodes.Count == 0 && currentNode.attributes.Count() == 0)
                    continue;

                //complex Type
                XmlSchemaComplexType currentType = new XmlSchemaComplexType();
                currentType.Name = currentNode.name;

                //contains text
                if (currentNode.containText)
                    currentType.IsMixed = true;

                //add attributes
                foreach (AttributeClass attr in currentNode.attributes)
                {
                    //check attribute name
                    if (!String.IsNullOrEmpty(attr.prefix))
                        continue;

                    XmlSchemaAttribute currentSchemaAttr = new XmlSchemaAttribute();
                    currentSchemaAttr.Name = attr.name;
                    currentSchemaAttr.SchemaTypeName = new XmlQualifiedName("string", defaultNamespace);

                    //required
                    if (attr.appearCount == currentNode.appearCount)
                        currentSchemaAttr.Use = XmlSchemaUse.Required;
                    else
                        currentSchemaAttr.Use = XmlSchemaUse.Optional;

                    //add attribute to schema
                    currentType.Attributes.Add(currentSchemaAttr);
                }

                //add child elements
                XmlSchemaSequence childElSequence = new XmlSchemaSequence();
                foreach (NodeAppearPair childNodeAppearPair in currentNode.childNodes)
                {
                    XmlSchemaElement currentSchemaEl = new XmlSchemaElement();
                    currentSchemaEl.Name = childNodeAppearPair.nodeClass.name;

                    //simple or complex type child
                    if (childNodeAppearPair.nodeClass.childNodes.Count == 0 && childNodeAppearPair.nodeClass.attributes.Count() == 0)
                        currentSchemaEl.SchemaTypeName = new XmlQualifiedName("string", defaultNamespace);
                    else
                        currentSchemaEl.SchemaTypeName = new XmlQualifiedName(childNodeAppearPair.nodeClass.name);

                    //min/maxOccurs
                    currentSchemaEl.MinOccurs = childNodeAppearPair.isRequired ? 1 : 0;

                    //maxOccurs
                    currentSchemaEl.MaxOccurs = childNodeAppearPair.maxAppearCount;

                    childElSequence.Items.Add(currentSchemaEl);
                }
                currentType.Particle = childElSequence;
                finalSchema.Items.Add(currentType);
            }

            finalSchema.Write(XmlWriter.Create(Path.Combine(logFolder, logPrefix + "Schema.xsd")), nsmgr);
        }
开发者ID:xchgdzq233,项目名称:testing,代码行数:79,代码来源:Program.cs


注:本文中的System.Xml.Schema.XmlSchema.Write方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。