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
124 views
in Technique[技术] by (71.8m points)

c# - Generating XML file using XSD file

How do you generate an XML file from an XSD file?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Suppose we have Test.xsd file that looks like this:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="MyClass">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Field1"
                    type="xs:string"/>
        <xs:element name="Field2"
                    type="xs:string"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
  1. Create classes using xsd tool:

    xsd.exe /classes Test.xsd
    

    This will generate Test.cs file.

  2. Add Test.cs file to your solution.

  3. Create instance of MyClass, defined in XSD schema and XmlSerialize it:

    using System.Xml.Serialization;
    // ...
    var data = new MyClass { Field1 = "test1", Field2 = "test2" };
    var serializer = new XmlSerializer(typeof(MyClass));
    using (var stream = new StreamWriter("C:\test.xml"))
        serializer.Serialize(stream, data);
    

Result:

<?xml version="1.0" encoding="utf-8"?>
<MyClass xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Field1>test1</Field1>
  <Field2>test2</Field2>
</MyClass>

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

...