Search The Blog
About this site

@RoyOsherove

Subscribe!

This site aims to connect all the dots of my online activities - from tools, books blogs and twitter accounts, to upcoming conferences, engagements and user group talks.

from 5whys.com
Twitter: @RoyOsherove
My Book: The Art of Unit Testing
Latest Posts
« I'm a Copy Cat | Main | CodeDOM is missing some stuff »
Wednesday
Mar262003

HOWTO: Create an XMLSerializer from a given XML string

Well, I got some great replies on my appearently rookie question..;) .I'll post them here for others to learn from. that's what it's all about , isn't it?

The Problem: Given an XML string, create an instance of the XMLSerializer class, allowing you to construct or serialize an object of a specific type.

There were two solutions right away. They both seem pretty darn obvious - once you read them :) thanks folks!

Solution 1: Use a stringBuilder Object to create a stream

By : Jan Tielens
You can use the StringBuilder to create a stream.

I use it with CodeDom too, like this:
Private Function GetVBCode(ByVal code As CodeTypeDeclaration) As String
Dim gen As New VBCodeProvider

Dim sb As New System.Text.StringBuilder
Dim stream As New IO.StringWriter(sb)
gen.CreateGenerator().GenerateCodeFromType(code, stream, Nothing)
stream.Close()

Return sb.ToString
End Function


Solution 2:  Use a MemoryStream Object to translate the string into a stream, which is needed to intialize the XMLSerializer

By Christian Weyer



[...]
string xmlString = @"<?xml version='1.0' encoding='utf-8' ?><TestType><Number>42</Number><Value>Christian</Value></TestType>";

System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.TextWriter writer = new System.IO.StreamWriter( ms );
writer.Write(xmlString);
writer.Flush();

ms.Seek(0, System.IO.SeekOrigin.Begin);
XmlSerializer serializer = new XmlSerializer(typeof(TestType));
TestType tt = (TestType)serializer.Deserialize(ms);
[...]

public class TestType
{
public int Number;
public string Value;
}

PrintView Printer Friendly Version

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>