Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
141 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:empautogen.xml"));
                Console.WriteLine("Autogenerated file is here : c:empautogen.xml");
            }            
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...