Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating XML file using XSD file

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

like image 324
sachin kulkarni Avatar asked Jun 30 '11 05:06

sachin kulkarni


People also ask

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.

Can we generate XML from XSD Python?

This is a simple python script to help you generate some xmls if you have a xsd. It uses the xmlschema library to parse the given schema document and then populate some hardcoded values.

How do I use an XSD file?

An XSD file stores its contents as plain text in XML format, which means the files can be opened and viewed by any text editor and numerous other programs. However, if you want to edit an XSD file, you should use an XML editor, such as Microsoft XML Notepad, Bare Bones BBEdit, or SyncRO Soft oXygen XML Editor.


1 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> 
  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> 
like image 87
Alex Aza Avatar answered Oct 08 '22 02:10

Alex Aza