Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a test XML from XML Schema programmatically

I have searched for a bit now, but i'm not able to find a way to autogenerate data from a XML Schema programmatically. Lets say I have this XML schema:

<xs:element xmlns:xs="http://www.w3.org/2001/XMLSchema" name ="Persons">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="Person">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="FirstName" type="xs:string" />
            <xs:element name="LastName" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element> 

I am able to create a XML from this using the VS function "Generate Sample XML" enter image description here
Is there a way to do this programmatically?

Edit: To specify. I do not want to create all the objects and insert data programmatically myself. I would like for it to create the objects and attributes automatically just like the "Generate Sample XML" in VS. The reason for this is that i would like to change the XSD without having to do anything about xml sample generation.

like image 650
Stian Standahl Avatar asked Jan 18 '13 07:01

Stian Standahl


People also ask

How do you generate sample XML from XSD in Notepad ++?

Open your XSD document. Switch to XML Schema Explorer. Right click the root node and choose "Generate Sample Xml"

Can we generate XML from XSD?

Just follow the below steps to get XML from XSD. Select XSD File in project, right click for Menu and select Generate > XML File… Provide the XML file Name and XML File location in the popup window. Click on next button.


1 Answers

after doing some searching. I have found a project that have implemented a xml sample generator. I created a test solution and imported the classes. Then i deleted the XmlGen.cs file and created my own main method. The output will be based on the root element.

public static void Main(string[] args)
        {
            using (var stream = new MemoryStream(File.ReadAllBytes("schema.xsd")))
            {
                var schema = XmlSchema.Read(XmlReader.Create(stream ), null);
                var gen = new XmlSampleGenerator(schema, new XmlQualifiedName("rootElement"));
                gen.WriteXml(XmlWriter.Create(@"c:\temp\autogen.xml"));
                Console.WriteLine("Autogenerated file is here : c:\temp\autogen.xml");
            }            
        }
like image 153
Stian Standahl Avatar answered Oct 06 '22 03:10

Stian Standahl