Infer class serves for infering XML Schema from given XML instance document.
Пример #1
0
        // http://stackoverflow.com/questions/22835730/create-xsd-from-xml-in-code
        // https://msdn.microsoft.com/en-us/library/xz2797k1%28v=vs.110%29.aspx
        private static void GenerateXsdFromXml(string xmlPath, string xsdPath)
        {
            var reader = XmlReader.Create(xmlPath);
            var inference = new XmlSchemaInference();
            var schemaSet = new XmlSchemaSet();
            schemaSet = inference.InferSchema(reader);
            reader.Dispose();

            using (var writer = XmlWriter.Create(xsdPath))
            {
                foreach (XmlSchema schema in schemaSet.Schemas())
                {
                    schema.Write(writer);
                }
            }
        }
 internal void InferSchema(XmlDocument xdoc, string[] excludedNamespaces, XmlReadMode mode)
 {
     IntPtr ptr;
     Bid.ScopeEnter(out ptr, "<ds.DataSet.InferSchema|INFO> %d#, mode=%d{ds.XmlReadMode}\n", this.ObjectID, (int) mode);
     try
     {
         string namespaceURI = xdoc.DocumentElement.NamespaceURI;
         if (excludedNamespaces == null)
         {
             excludedNamespaces = new string[0];
         }
         XmlNodeReader instanceDocument = new XmlIgnoreNamespaceReader(xdoc, excludedNamespaces);
         XmlSchemaInference inference = new XmlSchemaInference {
             Occurrence = XmlSchemaInference.InferenceOption.Relaxed
         };
         if (mode == XmlReadMode.InferTypedSchema)
         {
             inference.TypeInference = XmlSchemaInference.InferenceOption.Restricted;
         }
         else
         {
             inference.TypeInference = XmlSchemaInference.InferenceOption.Relaxed;
         }
         XmlSchemaSet schemaSet = inference.InferSchema(instanceDocument);
         schemaSet.Compile();
         XSDSchema schema = new XSDSchema {
             FromInference = true
         };
         try
         {
             schema.LoadSchema(schemaSet, this);
         }
         finally
         {
             schema.FromInference = false;
         }
     }
     finally
     {
         Bid.ScopeLeave(ref ptr);
     }
 }
        /// <summary>
        /// Helps in generating an XSD for a test format XML.
        /// </summary>
        private void createxsd()
        {
            XmlReader reader = XmlReader.Create("D:/response.xml");
            XmlSchemaSet schemaSet = new XmlSchemaSet();
            XmlSchemaInference schema = new XmlSchemaInference();
            schemaSet = schema.InferSchema(reader);
            var settings = new XmlWriterSettings();
            settings.Indent = true;

            foreach (XmlSchema s in schemaSet.Schemas())
            {
                using (var stringWriter = new StringWriter())
                {
                    using (var writer = XmlWriter.Create(stringWriter, settings))
                    {
                        s.Write(writer);
                    }

                    essayAnswerRexponseTxt.Visible = true;
                    essayAnswerRexponseTxt.Text = stringWriter.ToString();
                }
            }
        }
Пример #4
0
        internal void InferSchema(XmlDocument xdoc, string[] excludedNamespaces, XmlReadMode mode) {
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<ds.DataSet.InferSchema|INFO> %d#, mode=%d{ds.XmlReadMode}\n", ObjectID, (int)mode);
            try {
                string ns = xdoc.DocumentElement.NamespaceURI;
                if (null == excludedNamespaces) {
                    excludedNamespaces = new string[0];
                }
                XmlNodeReader xnr = new XmlIgnoreNamespaceReader(xdoc, excludedNamespaces);
                System.Xml.Schema.XmlSchemaInference infer = new System.Xml.Schema.XmlSchemaInference();

                infer.Occurrence = XmlSchemaInference.InferenceOption.Relaxed;

                if (mode == XmlReadMode.InferTypedSchema)
                    infer.TypeInference = XmlSchemaInference.InferenceOption.Restricted;
                else
                    infer.TypeInference = XmlSchemaInference.InferenceOption.Relaxed;

                XmlSchemaSet schemaSet = infer.InferSchema(xnr);
                schemaSet.Compile();

                XSDSchema schema = new XSDSchema();
                schema.FromInference = true;

                try {
                    schema.LoadSchema(schemaSet, this);
                }
                finally {
                    schema.FromInference = false; // this is always false if you are not calling fron inference
                }
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
        }
Пример #5
0
        protected XmlSchemaSet CreateSchemaSetFromXml(string XmlContent)
        {
            XmlSchemaInference infer = new XmlSchemaInference();
            StringReader s = new StringReader(XmlContent);

            return infer.InferSchema(XmlReader.Create(s));
        }
Пример #6
0
 public void InferConfigSchema()
 {
     XmlSchemaInference infer = new XmlSchemaInference();
     var schemaSet = infer.InferSchema(XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream("NHibernate.Tool.hbm2net.Tests.t4config.xml")));
     Assert.AreEqual(1, schemaSet.Schemas().Count);
     foreach (XmlSchema schema in schemaSet.Schemas())
     {
         schema.Write(Console.Out);
     }
 }
Пример #7
0
        private void InferSchemaFromXML(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();

            openFile.InitialDirectory = Application.ExecutablePath;
            openFile.Filter = "Xml files (*.xml)|*.xml|All files (*.*)|*.*";
            openFile.FilterIndex = 1;
            openFile.RestoreDirectory = true;

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                string fullName = openFile.FileName;
                try
                {
                    XmlReader reader = XmlReader.Create(fullName);
                    XmlSchemaSet schemaSet = new XmlSchemaSet();
                    XmlSchemaInference inference = new XmlSchemaInference();
                    schemaSet = inference.InferSchema(reader);
                    // Display the inferred schema.
                    using (FileStream stream = new FileStream("Schema.xsd", FileMode.OpenOrCreate))
                    {
                        foreach (XmlSchema schema in schemaSet.Schemas())
                        {
                            schema.Write(stream);
                        }
                    }
                    OpenFile("Schema.xsd", null);
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }

            }
        }
Пример #8
0
    private XDocument InferXMLDataType(string xml_text)
    {
      var schema = new XmlSchemaInference();
      XmlSchemaSet schemaSet = schema.InferSchema(XmlReader.Create(new System.IO.StringReader(xml_text)));

      var output = new System.IO.StringWriter();
      foreach (XmlSchema s in schemaSet.Schemas())
      {
        s.Write(output);
      }
      output.Flush();
      var xsd_text = output.GetStringBuilder().ToString();
      Trace.WriteLine($"XML Instance:{xml_text}");
      Trace.WriteLine($"Inferred XSD:{xsd_text}");
      Trace.WriteLine("");
      return XDocument.Parse(xsd_text);
    }
Пример #9
0
        private void inferXSDFromXMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*";
            openFileDialog.FilterIndex = 2;
            openFileDialog.RestoreDirectory = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Cursor = Cursors.WaitCursor;

                    //https://msdn.microsoft.com/en-us/library/system.xml.schema.xmlschemainference.aspx
                    XmlReader reader = XmlReader.Create(openFileDialog.FileName);
                    XmlSchemaSet schemaSet = new XmlSchemaSet();
                    XmlSchemaInference schema = new XmlSchemaInference();

                    schemaSet = schema.InferSchema(reader);

                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter = "xsd files (*.xsd) | *.xsd | All files(*.*) | *.* ";
                    saveFileDialog.FilterIndex = 0;
                    saveFileDialog.RestoreDirectory = true;
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        string outputFilename = saveFileDialog.FileName;
                        using (TextWriter textWriter = File.CreateText(outputFilename))
                        {
                            foreach (XmlSchema xmlSchema in schemaSet.Schemas())
                            {
                                xmlSchema.Write(textWriter);
                            }
                        }

                        if(MessageBox.Show(this, "Would you open the newly inferred XSD file?", "Open XSD file", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            LoadSchema(outputFilename);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                Cursor = Cursors.Default;
            }
        }
        private void createxsd()
        {
            XmlReader reader = XmlReader.Create("D:/DrivingLicense.xml");
            XmlSchemaSet schemaSet = new XmlSchemaSet();
            XmlSchemaInference schema = new XmlSchemaInference();
            System.IO.StreamWriter stringWriter = new System.IO.StreamWriter("D:/test.txt");
            schemaSet = schema.InferSchema(reader);
            var settings = new XmlWriterSettings();
            settings.Indent = true;

            foreach (XmlSchema s in schemaSet.Schemas())
            {
                    using (var writer = XmlWriter.Create(stringWriter, settings))
                    {
                        s.Write(writer);
                    }

                    stringWriter.Write(s);        
            }
        }
Пример #11
0
        private void toolStripButtonOpen1BillFile_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    lbxTESTSTRING.Items.Clear();
                    //Asn->Xml 
                    toolStripStatusLabel3.Text = "Asn To Xml......";
                    toolStripStatusLabel4.Text = appPath + "\\Exe\\asn2xml.exe  " + openFileDialog1.FileName + "  -o  " + appPath + "\\Temp\\Asn1OutXml.xml ";
                    Icdr.Conn.ModFuc.ExecuteCmd(toolStripStatusLabel4.Text);
                    StreamReader reader = new StreamReader(appPath + "\\Temp\\Asn1OutXml.xml");
                    int i = 0;
                    while (!reader.EndOfStream)
                    {
                        lbxTESTSTRING.Items.Add(reader.ReadLine());
                        i++;
                        Application.DoEvents();
                        if (i == 100) { break; }
                    }
                    reader.Close();
                    while (!File.Exists(appPath + "\\Temp\\Asn1OutXml.xml"))
                    { Application.DoEvents(); }
                    XmlReader reader1 = XmlReader.Create(appPath + "\\Temp\\Asn1OutXml.xml");
                    XmlSchemaSet schemaSet = new XmlSchemaSet();
                    XmlSchemaInference schema = new XmlSchemaInference();
                    schemaSet = schema.InferSchema(reader1);
                    XmlSchema compiledSchema = null;

                    foreach (XmlSchema s in schemaSet.Schemas())
                    {
                        compiledSchema = s;
                        lbxXsd.Items.Add(s.Elements.Names.ToString());

                        foreach (XmlSchemaObject schemaObject in compiledSchema.Items)
                        {
                            lbxXsd.Items.Add(schemaObject.SourceUri.Length+schemaObject.ToString().Length);
                            if (schemaObject.GetType() == typeof(XmlSchemaSimpleType))
                            {
                                XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)schemaObject;
                                lbxXsd.Items.Add("{0} {1}" + simpleType.Name + simpleType.Datatype.ValueType);
                            }
                            if (schemaObject.GetType() == typeof(XmlSchemaComplexType))
                            {
                                XmlSchemaComplexType complexType = (XmlSchemaComplexType)schemaObject;
                                lbxXsd.Items.Add("{0} {1}" + complexType.Name + complexType.Datatype.ValueType);
                            }
                        }
                    }

                    //regNum = reader.ReadLine();
                    // DataSet ds = new DataSet();
                    // ds.ReadXml (appPath + "\\Temp\\Asn1OutXml.xml");
                    // DataTable dt=ds.Tables [0];
                    // for (int i = 0; i < dt.Rows.Count; i++)
                    // {
                    //     lbxTESTSTRING.Items.Add(dt.Rows[i].ToString());
                    // }
                    //xParser.LoadData(openFileDialog1.FileName);
                }
                catch (Exception ex)
                {
                    string msg = ex.Message;
                    MessageBox.Show(msg);
                }
            }
        }
		private bool ProcessPasteSchemaRequest()
		{
			try
			{
				if (currentProject == null)
				{
					MessageBox.Show(
						"You cannot paste schema items outside of a project.",
						"Web Services Contract-First Paste Schema",
						MessageBoxButtons.OK,
						MessageBoxIcon.Exclamation);

					return true;
				}

				IDataObject dataObject = Clipboard.GetDataObject();
				if (dataObject == null)
				{
					MessageBox.Show(
						"There was no data found in the clipboard.",
						"Web Services Contract-First Paste Schema",
						MessageBoxButtons.OK,
						MessageBoxIcon.Exclamation);

					return true;
				}

				string xml = (string)dataObject.GetData(typeof(string));
				if (xml == null)
				{
					MessageBox.Show(
						"There was no string data found in the clipboard.",
						"Web Services Contract-First Paste Schema",
						MessageBoxButtons.OK,
						MessageBoxIcon.Exclamation);

					return true;
				}

				XElement schemaXml;
				try
				{
					schemaXml = XElement.Parse(xml);
				}
				catch (Exception)
				{
					MessageBox.Show(
						"The data found in the clipboard is not valid XML.",
						"Web Services Contract-First Paste Schema",
						MessageBoxButtons.OK,
						MessageBoxIcon.Exclamation);

					return true;
				}

				XmlSchemaSet schemas = new XmlSchemaSet();
				XmlSchemaInference inference = new XmlSchemaInference();

				using (XmlReader reader = schemaXml.CreateReader())
				{
					inference.InferSchema(reader, schemas);
				}

				XmlWriterSettings settings = new XmlWriterSettings { Indent = true };

				foreach (XmlSchema schema in schemas.Schemas())
				{
					if (schema.Items.Count == 0) continue;

					string schemaName = ((XmlSchemaElement)(schema.Items[0])).Name;
					string fileName = Path.Combine(selectedItem.Directory, Path.ChangeExtension(schemaName, "xsd"));

					if (File.Exists(fileName))
					{
						DialogResult dialogResult = MessageBox.Show(
							"A file named '" + Path.GetFileName(fileName) + "' already exist in the project. Do you want to overwrite this file?",
							"Web Services Contract-First Paste Schema",
							MessageBoxButtons.YesNo,
							MessageBoxIcon.Question);

						if (dialogResult == DialogResult.No) continue;
					}

					using (XmlWriter writer = XmlWriter.Create(fileName, settings))
					{
						if (writer != null)
						{
							schema.Write(writer);
						}
					}
					if (File.Exists(fileName))
					{
						currentProject.AddFile(fileName);
					}
				}
			}
			catch (Exception ex)
			{
				AppLog.LogMessage(ex.ToString());
				MessageBox.Show(ex.ToString(), "Web Services Contract-First Paste Schema", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			return true;
		}
Пример #13
0
    public void inferXSD_1()
    {
      var xml = @"<bookstore xmlns='http://www.contoso.com/books'>
  <book genre='autobiography' publicationdate='1981-03-22' ISBN='1-861003-11-0'>
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre='novel' publicationdate='1967-11-17' ISBN='0-201-63361-2'>
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre='philosophy' publicationdate='1991-02-15' ISBN='1-861001-57-6'>
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>";
      XmlReader reader = XmlReader.Create(new System.IO.StringReader(xml));
      XmlSchemaSet schemaSet = new XmlSchemaSet();
      XmlSchemaInference schema = new XmlSchemaInference();

      schemaSet = schema.InferSchema(reader);
      var output = new System.IO.StringWriter();
      foreach (XmlSchema s in schemaSet.Schemas())
      {
        s.Write(output);
      }
      output.Flush();
      var xsd_text = output.GetStringBuilder().ToString();
      Trace.WriteLine(xsd_text);
      var xsd = XDocument.Parse(xsd_text);
      Assert.IsNotNull(xsd);
    }
Пример #14
0
        public bool CanConvert(string xml)
        {
            bool isSchema = false;
            schemas = new XmlSchemaSet();
            List<XElement> instances = new List<XElement>();
            
            xml = xml.Trim();

            // Figure out if we have valid XML instance or XML schema
            try
            {
                instances.Add(XElement.Parse(xml));

                if (instances[0].Name.LocalName.Equals("schema") && instances[0].Name.NamespaceName.Equals("http://www.w3.org/2001/XMLSchema"))
                {
                    isSchema = true;
                }
            } 
            catch (XmlException)
            {
                try
                {
                    // Could be two separate XML instances back to back with no root node, check for that
                    XElement fakeRoot = XElement.Parse("<Root>" + xml + "</Root>");
                    foreach (XElement child in fakeRoot.Elements())
                    {
                        instances.Add(child);
                    }

                }
                catch (XmlException e)
                {
                    //RtlAwareMessageBox.Show(
                    PublicDI.log.error("Could not parse clipboard content as a XML instance. Please ensure the clipboard contains a valid XML instance." + Environment.NewLine + Environment.NewLine + e.Message);
                    //, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
                    return false;
                }
            }

            if (isSchema)
            {

                AddSchemasForPrimitiveTypes(schemas);

                try
                {
                    schemas.Add(null, instances[0].CreateReader());
                    schemas.Compile();
                }
                catch (Exception exception)
                {
                    if (exception is XmlException || exception is XmlSchemaException)
                    {
                        //RtlAwareMessageBox.Show
                            PublicDI.log.error("Could not parse clipboard content as a XML Schema. Please ensure the clipboard contains valid XML Schema." +
                            Environment.NewLine + Environment.NewLine + exception.Message);
                        //, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
                        return false;
                    }
                    else
                    {
                        // Rethrow unknown exceptions
                        throw;
                    }
                }


                RemoveComplexTypeSchemaIfNotUsed(schemas);

            }
            else
            {
                XmlSchemaInference inference = new XmlSchemaInference();

                try
                {
                    foreach (XElement element in instances)
                    {
                        schemas = inference.InferSchema(element.CreateReader(), schemas);
                    }

                    schemas.Compile();
                }
                catch (Exception exception)
                {
                    if (exception is XmlException || exception is XmlSchemaInferenceException)
                    {
                        //RtlAwareMessageBox.Show(
                        PublicDI.log.error("Could not infer the structure of the XML instance on the clipboard. Please consider modifying the instance." + Environment.NewLine + Environment.NewLine + exception.Message);                    
                        //    , "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
                        return false;
                    }
                    else
                    {
                        // Rethrow unknown exceptions
                        throw;
                    }
                }
            }

            return true;
        }
Пример #15
0
        /// <summary>
        /// Infers the schema.
        /// </summary>
        private void InferSchema()
        {
            string schemaText = string.Empty;
            string schemaError = string.Empty;

            XmlSchemaInference infer = new XmlSchemaInference();
            XmlTextReader xmlReader = new XmlTextReader(m_fileName);
            XmlSchemaSet schemas = null;

            try
            {
                schemas = infer.InferSchema(xmlReader);
            }
            catch (Exception exception)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine(exception.Message);
                builder.AppendLine(exception.StackTrace);
                schemaError = builder.ToString();
            }
            finally
            {
                xmlReader.Close();
            }

            if (schemas != null)
            {
                schemaText = GetSchemaString(schemas);
            }

            if (m_infererOutputDelegate != null)
            {
                m_infererOutputDelegate(schemaText, schemaError);
            }
        }
Пример #16
0
		/// <summary>
		/// Creates a schema based on the xml content.
		/// </summary>
		/// <returns>A set of generated schemas or null if the xml content is not
		/// well formed.</returns>
		public string[] InferSchema()
		{
			ITextEditor editor = TextEditor;
			if (editor == null)	return null;
			
			TaskService.ClearExceptCommentTasks();
			if (IsWellFormed) {
				try {
					using (XmlTextReader reader = new XmlTextReader(new StringReader(editor.Document.Text))) {
						XmlSchemaInference schemaInference = new XmlSchemaInference();
						XmlSchemaSet schemaSet = schemaInference.InferSchema(reader);
						return GetSchemas(schemaSet, editor);
					}
				} catch (XmlSchemaInferenceException ex) {
					AddTask(editor.FileName, ex.Message, ex.LinePosition, ex.LineNumber, TaskType.Error);
				}
			}
			ShowErrorList();
			return null;
		}
Пример #17
0
        internal void InferSchema(XmlDocument xdoc, string[] excludedNamespaces, XmlReadMode mode)
        {
            long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataSet.InferSchema|INFO> {0}, mode={1}", ObjectID, mode);
            try
            {
                string ns = xdoc.DocumentElement.NamespaceURI;
                if (null == excludedNamespaces)
                {
                    excludedNamespaces = Array.Empty<string>();
                }
                XmlNodeReader xnr = new XmlIgnoreNamespaceReader(xdoc, excludedNamespaces);
                XmlSchemaInference infer = new XmlSchemaInference();

                infer.Occurrence = XmlSchemaInference.InferenceOption.Relaxed;

                infer.TypeInference = (mode == XmlReadMode.InferTypedSchema) ?
                    XmlSchemaInference.InferenceOption.Restricted :
                    XmlSchemaInference.InferenceOption.Relaxed;

                XmlSchemaSet schemaSet = infer.InferSchema(xnr);
                schemaSet.Compile();

                XSDSchema schema = new XSDSchema();
                schema.FromInference = true;

                try
                {
                    schema.LoadSchema(schemaSet, this);
                }
                finally
                {
                    schema.FromInference = false; // this is always false if you are not calling fron inference
                }
            }
            finally
            {
                DataCommonEventSource.Log.ExitScope(logScopeId);
            }
        }