Beispiel #1
0
        public static XmlDocument generateCleanXml(string xml, string xsd, string schemarelativepath)
        {
            using (XmlTextWriter textWriter = new XmlTextWriter(xml, null))
            {
                textWriter.Formatting = Formatting.Indented;
                XmlSampleGenerator generator = new XmlSampleGenerator(xsd, null);
                generator.MaxThreshold = 0;
                generator.WriteXml(textWriter);
            }

            // adjust xml directly
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load(xml);
                XmlAttribute schemaReference = doc.CreateAttribute("noNamespaceSchemaLocation", xsiNamespace);
                string fileName = schemarelativepath + @"\" + xsd.Substring(xsd.LastIndexOf('\\') + 1);
                schemaReference.Value = fileName;
                doc.DocumentElement.Attributes.Append(schemaReference);
                doc.Save(xml);
            }
            catch { _log.Error("Sample document could not be loaded. Path: " + xml); }

            return doc;
        }
Beispiel #2
0
        public static void Main(string[] args)
        {
            XmlSchemaSet schemas = new XmlSchemaSet();
            XmlQualifiedName qname = XmlQualifiedName.Empty;
            string localName = string.Empty;
            string ns = string.Empty;
            int max = 0;
            int listLength = 0;

            for (int i = 0; i < args.Length; i++) {
                string arg = args[i];
                string value = string.Empty;
                bool argument = false;

                if (arg.StartsWith("/") || arg.StartsWith("-")) {
                    argument = true;
                    int colonPos = arg.IndexOf(":");
                    if (colonPos != -1) {
                        value = arg.Substring(colonPos + 1);
                        arg = arg.Substring(0, colonPos);
                    }
                }
                arg = arg.ToLower(CultureInfo.InvariantCulture);
                if (!argument && arg.EndsWith(".xsd")) {
                    schemas.Add(null, args[i]);
                }
                else if (ArgumentMatch(arg, "?") || ArgumentMatch(arg, "help")) {
                    WriteHelp();
                    return;
                }
                else if (ArgumentMatch(arg, "localname")) {
                    localName = value;
                }
                else if (ArgumentMatch(arg, "namespace")) {
                    ns = value;
                }
                else if (ArgumentMatch(arg, "maxthreshold")) {
                    max = Int16.Parse(value);
                }
                else if (ArgumentMatch(arg, "listlength")) {
                    listLength = Int16.Parse(value);
                }
                else {
                    throw new ArgumentException(args[i]);
                }
            }

            if (args.Length == 0) {
                WriteHelp();
                return;
            }
            XmlTextWriter textWriter = new XmlTextWriter("Sample.xml", null);
            textWriter.Formatting = Formatting.Indented;
            XmlSampleGenerator genr = new XmlSampleGenerator(schemas, qname);
            if (max > 0) genr.MaxThreshold = max;
            if (listLength > 0) genr.ListLength = listLength;
            genr.WriteXml(textWriter);
        }
Beispiel #3
0
        /// <summary>
        /// Generates a new xml document and writes it to a string.
        /// This is usefull when only needing a part of the new xml file.
        /// </summary>
        /// <param name="source">The schema file.</param>
        /// <returns>the Xml document representing the newly created xml.</returns>
        public static XmlDocument generateCleanXmlToString(string source)
        {
            XmlDocument doc = new XmlDocument();

            using (var sw = new StringWriter())
            {
                using (var xw = XmlWriter.Create(sw))
                {
                    XmlSampleGenerator generator = new XmlSampleGenerator(source, null);
                    generator.WriteXml(xw);
                    doc.LoadXml(sw.ToString());
                    XmlAttribute schemaReference = doc.CreateAttribute("noNamespaceSchemaLocation", xsiNamespace);
                    schemaReference.Value = (new Uri(Assembly.GetEntryAssembly().Location)).MakeRelativeUri(new Uri(source)).ToString().Replace(@"Resources/DocUI/", "");
                    doc.DocumentElement.Attributes.Append(schemaReference);
                }

            }

            return doc;
        }
        /// <summary>
        /// Generates Sample XML from XSD schema, when started from the same folder as the xsd document
        /// you can use no parameters for the default configuration
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// When no xsd file is found in the given path or in the root folder this exception is thrown
        /// </exception>
        /// <param name="args[0]">ElementName - the name of the element to generate</param>
        /// <param name="args[1]">MaxTreshold - how many elements to create</param>
        /// <param name="args[2]">
        /// ListLength - defines how many items should be generated for a simple type of variety
        /// list. The default value of this property is 5
        /// </param>
        /// <param name="args[3]">XSD file - file to open</param>
        /// <param name="args[4]">Folder to save to</param>
        /// of variety list</param>
        static void Main(string[] args)
        {
            Console.WriteLine("Usage: ");
            Console.WriteLine("XmlGen.exe element, maxCount, innerListsLength, xsdSchemaPath, folderName");
            Console.WriteLine();
            Console.WriteLine("element - expected root element(a complexType) for the generated xml");

            Console.WriteLine("maxCount - number of items to be generated for elements that have a");
            Console.WriteLine("maxOccurs attribute set to a value default value 10");

            Console.WriteLine("innerListLength - defines how many items should be generated for a simple");
            Console.WriteLine("type of variety list. The default value of this property is 5");

            Console.WriteLine("xsdSchemaPath - path to the xsd schema to use as template");

            Console.WriteLine("folderName - folder to save the generated xml");
            Console.WriteLine();
            Console.WriteLine("This program can run without input arguments as long as it is in the same");
            Console.WriteLine("folder as the xsd schema");
            Console.WriteLine();

            OrganizeInputArgs(args);

            var root = new XmlQualifiedName(rootElementName);

            var generator = new XmlSampleGenerator(schemaPath, root);
            generator.MaxThreshold = maxTreshold;
            generator.ListLength = listLength;

            using (var xmlWriter = new XmlTextWriter("Sample.xml", Encoding.UTF8))
            {
                xmlWriter.Formatting = Formatting.Indented;

                generator.WriteXml(xmlWriter);
            }

            Console.WriteLine("Success\n");
        }
        private void DeserializeSampleXml(string pattern, Assembly assembly)
        {
            var files = Glob.Glob.ExpandNames(pattern);

            var set = new XmlSchemaSet();

            var schemas = files.Select(f => XmlSchema.Read(XmlReader.Create(f), (s, e) =>
            {
                Assert.True(false, e.Message);
            }));

            foreach (var s in schemas)
            {
                set.Add(s);
            }

            set.Compile();

            foreach (var rootElement in set.GlobalElements.Values.Cast<XmlSchemaElement>().Where(e => !e.IsAbstract))
            {
                var type = FindType(assembly, rootElement.QualifiedName);
                var serializer = new XmlSerializer(type);
                var generator = new XmlSampleGenerator(set, rootElement.QualifiedName);
                var sb = new StringBuilder();
                using (var xw = XmlWriter.Create(sb, new XmlWriterSettings { Indent = true }))
                {
                    // generate sample xml
                    generator.WriteXml(xw);
                    var xml = sb.ToString();

                    File.WriteAllText("xml.xml", xml);

                    // deserialize from sample
                    var sr = new StringReader(xml);
                    var o = serializer.Deserialize(sr);

                    // serialize back to xml
                    var xml2 = Serialize(serializer, o);

                    File.WriteAllText("xml2.xml", xml2);

                    // validate serialized xml
                    XmlReaderSettings settings = new XmlReaderSettings();
                    settings.ValidationType = ValidationType.Schema;
                    settings.Schemas = set;
                    settings.ValidationEventHandler += (s, e) =>
                    {
                        // generator doesn't generate valid values where pattern restrictions exist, e.g. email
                        if (!e.Message.Contains("The Pattern constraint failed"))
                            Assert.True(false, e.Message);
                    };

                    XmlReader reader = XmlReader.Create(new StringReader(xml2), settings);
                    while (reader.Read()) ;

                    // deserialize again
                    sr = new StringReader(xml2);
                    var o2 = serializer.Deserialize(sr);

                    AssertEx.Equal(o, o2);
                }
            }
        }