Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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");
            }            
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...