SQL Server DB to XSD - can it be done thru code

  • Thread starter Thread starter sippyuconn
  • Start date Start date
S

sippyuconn

Hi

In C# ide if you have a SqlServer attached and Create a New XSD Item in a
solution you can then drag a db from the SQLServer and ti creates a XSD
modelled after the db. Can this be done thru code???

If I have a EXE that is passed a db can I generate a XSD on the fly???

Thanks
 
sippyucon,

You ^might^ be able to get it through a call to GetSchema on a
SqlConnection. This will return a DataTable, which you might be able to use
to create the XSD schema for the table in question.

My guess, though, is that this won't give you what you want, and that
the functionality you are seeing is IDE-specific, and not accessible through
the framework (which means you will have to do this on your own).
 
You can generate a schema from a DataSet, so either construct one in code or
Fill one with a DataAdapter and call the GetXmlSchema function which returns
it as a string.

e.g:

DataSet ds = new DataSet();

ds.Tables.Add("table 1");
ds.Tables[0].Columns.Add("col1", typeof(int));
ds.Tables[0].Columns.Add("col2", typeof(DateTime));
ds.Tables[0].Columns.Add("col3", typeof(string));
ds.Tables[0].Columns.Add("col4", typeof(Guid));

File.WriteAllText("C:\\sch.xsd",ds.GetXmlSchema());



this makes:

<?xml version="1.0" encoding="utf-16"?>
<xs:schema id="NewDataSet" xmlns=""
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true"
msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="table_x0020_1">
<xs:complexType>
<xs:sequence>
<xs:element name="col1" type="xs:int" minOccurs="0" />
<xs:element name="col2" type="xs:dateTime" minOccurs="0" />
<xs:element name="col3" type="xs:string" minOccurs="0" />
<xs:element name="col4" msdata:DataType="System.Guid,
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
 
that creates a xml including the schema:

SELECT * from [tablename] FOR XML AUTO, XMLSCHEMA, ELEMENTS, ROOT
('tablename')
 
Back
Top