Thursday, February 28, 2008

Just a random piece of code that I thought is handy: when you are experimenting with xml, you probably want to see the xml quickly and easily. For instance, when you are using the DataContractSerializer to serialize a type, you want to see how it looks. But it get's printed on one line!! That's not useful.

Use something like the following code:

            MemoryStream m = new MemoryStream();
            XmlTextWriter tw = new XmlTextWriter(m, Encoding.UTF8);
            tw.Formatting = Formatting.Indented;
            tw.Indentation = 4;
            tw.IndentChar = " ".ToCharArray()[0];
            s.WriteObject(tw, p);
            tw.Flush();
            m.Position = 0;
            StreamReader sr = new StreamReader(m);
            string strOutput = sr.ReadToEnd();
            Debug.WriteLine(strOutput);
 
Where s represents your datacontract serializer.
This outputs glorious xml to the debug.output window:
<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/DomainModel">
    <FirstName>Ruurd</FirstName>
    <LastName>Boeke</LastName>
    <Orders>
        <Order>
            <Amount>5</Amount>
            <ProductID>10</ProductID>
        </Order>
        <Order>
            <Amount>12</Amount>
            <ProductID>11</ProductID>
        </Order>
        <Order>
            <Amount>2</Amount>
            <ProductID>1</ProductID>
        </Order>
    </Orders>
</Person>
Thursday, February 28, 2008 5:45:02 PM (Romance Standard Time, UTC+01:00)
Looks like a real nice candidate for a static extension method on the Debug class...
Jochen Zeischka
Thursday, February 28, 2008 5:53:45 PM (Romance Standard Time, UTC+01:00)
guess what? That's exactly what I was thinking ;-)
Ruurd Boeke
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):