| Servergeek |
| Mickey Williams' weblog |
|
My C# BookMicrosoft Press PageOn Amazon Racing LinksSlalomSkateboarder.comNCDSA slalom page 3dm Ick Sticks Pocket Pistols .NETScott GuthrieRob Howard .NET Notes BradA LonghornScobleChris Sells ServicesDon BoxChristian Weyer All Things Distributed Ingo Rammer Tim Ewald BlawgsBag and BaggageSCOTUS Blog EconArg MaxCapital Spectator OtherWilliam Gibson |
Thursday, March 27, 2003
XML serialization with a validating readerPosted 5:44 PMXML serialization is so brain-dead easy in .NET that you sometimes forget that XML is still crufted together by lesser platforms. Here's the basic boilerplate for serialization while validating against XML schema: Given a simple XML document: <xml version="1.0"?> <Foo> <n>42</n> <s>zaphod</s> </Foo>Create a simple schema, here the element 'n' must exist once:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Foo">
<xs:complexType>
<xs:sequence>
<xs:element name="n" type="xs:int"/>
<xs:element name="s" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
And deserialize like this:
using(FileStream stream = new FileStream("C:\\foo.xml", FileMode.Open))
{
XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(stream));
reader.Schemas.Add(null, "c:\\foo.xsd");
reader.ValidationType = ValidationType.Schema;
XmlSerializer s = new XmlSerializer(typeof(Foo));
Foo f = (Foo)s.Deserialize(reader);
....
}
Turning an array of objects into a DataTablePosted 5:40 PMIn the previous incarnation of the blog, I had a similar example. I've got a couple of non-programming posts, but first I need to build up my geek index: private DataTable f(MyObject[] objs) { DataTable tab = new DataTable(); // For each interesting item in the table, create // a column tab.Columns.Add("ID", typeof(int)); ... // After the table schema is created, // add a new row for each array element foreach(MyObject obj in objs) { DataRow row = tab.NewRow(); row[0] = obj.ID; // and so on ... tab.Rows.Add(row); } return tab; }
|