How do you generate an XML file from an XSD file?
3 Answers
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>
Create classes using xsd tool:
xsd.exe /classes Test.xsd
This will generate Test.cs file.
Add Test.cs file to your solution.
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>

- 3,894
- 22
- 31

- 76,499
- 26
- 155
- 134
-
Hi Alex Thanks for the reply .I have few doubts.Where should I execute the command xsd.exe /classes Test.xsd .Secondly I could not co relate the class in Test.cs and MyClass. – sachin kulkarni Jun 30 '11 at 06:09
-
@sachin kulkarni - what doubts do you have? – Alex Aza Jun 30 '11 at 06:12
-
What is the tool Xsd.exe?Where shall I get that? – sachin kulkarni Jun 30 '11 at 06:27
-
2[XML Schema Definition Tool](http://msdn.microsoft.com/en-us/library/x6c1kb0s%28v=VS.100%29.aspx) – Alex Aza Jun 30 '11 at 06:29
-
7You can find it at `C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin`, or just use Visual Studio Command Prompt. – Alex Aza Jun 30 '11 at 06:33
-
2from MSDN how to access VS Command Prompt : http://msdn.microsoft.com/en-us/library/ms229859(v=vs.110).aspx – Maher Abuthraa Jan 23 '14 at 08:13
-
What if you need MyClass repeated several times? Is it possible to connect c# code and xsd in this case? I guess class would not be enough in this case, but List of classes. – FrenkyB May 21 '19 at 05:56
this is the path to xsd.exe file, be sure you have installed SDK.
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools (here is the xsd.exe (application))
also see this if needed. where to find xsd.exe in visual studio 2013 on windows 8

- 1
- 1
For "Create classes using xsd tool: xsd.exe /classes Test.xsd" firstly come to windows Start then write "Developer.." after that you will see Developer Command Prompt for Vs2015(your version). run this command into the command.
In addititon if your xsd file is big, it takes time to define all elements. In my situation I am trying implement database column in each elemnen for getting information for each customer of my compnay. (var data = new MyClass { Field1 = "test1", Field2 = "test2" };)