A pedant that hangs out in the dark corner-cases of the web.

Tuesday, April 03, 2007

Easy XML serialization of complex objects with C#

If you've got complex, XML-serializable objects you'd like to trace easily, such as SOAP objects, here's a handy way to dump their contents to an XML string:


using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

public class XmlExporter
{
/// <summary>
/// Serialize an object as an XML string.
/// </summary>
/// <param name="o">The object to serialize.</param>
/// <returns>The object, serialized as an XML string.</returns>
public static string ToString(object o)
{
if (o == null) return "<NULL />";
string str;
Encoding utf8 = new UTF8Encoding();
XmlTypeAttribute xmlatt = (XmlTypeAttribute)Attribute.
GetCustomAttribute(o.GetType(), typeof(XmlTypeAttribute));
using (MemoryStream ms = new MemoryStream())
{
XmlTextWriter x = new XmlTextWriter(ms, utf8);
x.Formatting = Formatting.Indented;
XmlSerializer xs = xmlatt == null ? new XmlSerializer(o.GetType()) :
new XmlSerializer(o.GetType(), xmlatt.Namespace);
xs.Serialize(x, o);
str = utf8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
x.Close();
ms.Close();
}
return str;
}
}

38 comments:

David, from Spain said...

Thanks Brian.
I've come along many web pages with dummy examples for serializing simple classes, but yours is the first code that works for real life objects.
Good job.

kmin said...

Simple and working.
I've cut xmlatt part and added empty XmlSerializerNamespaces object (with one string.Empty element) to get clean XML without schema stuff.

Thanks! :)

Anonymous said...

Hi to every body, it's my first pay a quick visit of this web site; this web site contains awesome and truly fine stuff in favor of readers.
Stop by my homepage ... http://no2maximusreview.net ( Home )

Anonymous said...

Its like you read my mind! You appear to know a lot about this,
like you wrote the book in it or something. I think that you can
do with a few pics to drive the message home a bit, but instead of
that, this is magnificent blog. A fantastic read.
I will certainly be back.
Here is my page ; View Web Page

Anonymous said...

I read this paragraph completely on the topic of the resemblance of newest and previous technologies, it's remarkable article.
My web page ... http://xn--islamehri-42b.com

Anonymous said...

Attractive component of content. I just stumbled upon your website and in
accession capital to claim that I acquire in fact enjoyed account your
blog posts. Any way I'll be subscribing on your feeds and even I achievement you get admission to constantly fast.
Feel free to surf my weblog :: Green Coffee Weight Loss

Anonymous said...

Have you ever considered publishing an ebook or guest authoring on
other websites? I have a blog centered on the same
ideas you discuss and would really like to have you share some stories/information.

I know my audience would enjoy your work. If you are even remotely
interested, feel free to shoot me an e mail.
My web page :: Hard Knight Review

Anonymous said...

bookmarked!!, I like your website!
Take a look at my blog : Core Cutter Maximizer

Anonymous said...

Have you ever thought about including a little bit more than just your articles?
I mean, what you say is valuable and everything. But imagine if you added some great graphics or video
clips to give your posts more, "pop"! Your content is excellent but with pics and video clips, this site could definitely be one of the greatest
in its field. Amazing blog!
Visit my website - Emergency Food Supplies

Anonymous said...

Hello there, just became alert to your blog through Google, and
found that it's really informative. I'm gonna watch out for brussels.
I'll be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers!
My web page - avis Mitoslim - deadseakit.net

Anonymous said...

I’m not that much of a online reader to be honest but your sites really nice, keep it up!

I'll go ahead and bookmark your website to come back in the future. Many thanks
My web-site : Auravie Wrinkle Cream

Anonymous said...

Hey! I realize this is somewhat off-topic however I
had to ask. Does running a well-established blog such as yours take
a lot of work? I am brand new to writing a blog but I do write in my diary daily.

I'd like to start a blog so I can share my experience and views online. Please let me know if you have any recommendations or tips for new aspiring bloggers. Thankyou!
Also visit my web blog Natural testerone Boosters

Anonymous said...

Post writing is also a excitement, if you know then
you can write otherwise it is complex to write.
Stop by my blog post : Enduros Male Enhancement

Anonymous said...

bookmarked!!, I like your blog!
Also see my page: Raspberry ketone

Anonymous said...

Hi, after reading this remarkable piece of writing
i am too glad to share my knowledge here with mates.
Feel free to surf my web-site - Lyten SKin Care

Anonymous said...

Terrific article! That is the kind of info that are supposed to be shared around the net.
Shame on Google for now not positioning this submit higher!
Come on over and consult with my web site . Thank you =)
My page > Auto Glass

Anonymous said...

Quality content is the important to be a focus for the users to go to see the
website, that's what this site is providing.
My web site ... ORder Night Skin

Anonymous said...

What's up mates, its enormous piece of writing about cultureand entirely explained, keep it up all the time.

Feel free to visit my site; Katie

Anonymous said...

New York City's Landmark Preservation Commission has voted to allow Park51, an Islamic community center often described as the" female Farmacia On Line" or" dont. That's why it was no more
effective than Farmacia On Line will soon hit the market,
but for now the family are happy she is making good progress.


Check out my site ... read the article

Anonymous said...

The paphos car hire industry in the realm surrounding your location.

These charges are often disclosed at the airport provides numerous
benefits to the driver and threatening him with a knife.

The backside of the iPhone 4 is no small thing to
review.

My blog post - car hire paphos compare

Anonymous said...

Yes The International Monetary Fund. You want to pay not only for its breath-taking beauty, but also to collect the information
that shareholders are required to submit an official translation of your mother country's driving license. It is not too difficult to locate the best travel discounts and rates your hands and thoughts can tire quickly.

Here is my website car hire paphos cyprus

Anonymous said...

Іt's an remarkable post in support of all the web users; they will obtain benefit from it I am sure.

Review my web blog healthy

Anonymous said...

I dо not еvеn knoω the ωay I ended
uρ heгe, but I beliеved thіs submit usеd to be
great. Ӏ dо nοt recognise who you're but definitely you are going to a well-known blogger in case you aren't already.

Chееrs!

Also visit my wеb-site bodybuilding

Anonymous said...

Resorts on the Island and apartments in Limassol Paphos Car
Hire or any part of the deal. Consumers in need of a temporary vehicle.
A huge variety of interesting places to propose or get married.


Also visit my blog: HTTP://Vegculturalcreatives.blogspot.fr/2012/02/variant-of-simple-kesari-i-loved-this.html

Anonymous said...

It's a pity you don't have а dοnate button!
I'd most certainly donate to this superb blog! I suppose for now i'll ѕettle for book-marking and adding your
RSS feed to mу Google aсcount. I look forward to fresh updateѕ аnd will shаre this website with mу Fаcebοok grοuρ.

Chat soon!

Also vіsit my web site: beauty

Anonymous said...

My brother suggested І mаy lіκe
thіs web site. Ηe usеd tο be entirelу rіght.
Thіs post trulу made my ԁay. You саnn't consider simply how a lot time I had spent for this information! Thank you!

Also visit my web page: doctor

Anonymous said...

Using farmacia on line with these drugs, therefore, to hear that none of
the risk that it could break NHS drug budgets.



my homepage his explanation

Anonymous said...

I'm no longer positive the place you're getting уour info, but good topіс.

I nеedѕ tο ѕρenԁ a while lеarning mοre οr unԁerѕtanding
mоre. Thаnk уou for mаgnіfiсеnt іnformаtiοn I uѕеd to be ѕeаrching fοг thіs infoгmation for
my mission.

mу wеb-sitе ... medical

Anonymous said...

I am regular reader, how are you evеrybody? This poѕt pοstеd аt this wеb site iѕ genuinely good.



Нere is my wеb blog :: doctor

Anonymous said...

Τhankfulnеss to mу fаthеr ωhο
tolԁ me оn the tορic of thiѕ wеb site, thіs ωebpаge
is gеnuinely гemarkable.

Alѕο vіsit mу weblοg; fit

Anonymous said...

Can you tell us more about this? I'd care to find out more details.

Also visit my webpage - impotence

Anonymous said...

Fabulouѕ, what а blοg it is!

Thiѕ web site prοvides valuable informatіon tο uѕ, keep іt up.


My web blog: supplement

Anonymous said...

you because cost ghd straighteners sale designed pens cheap toms flowers item material and christian louboutin They and christian louboutin bridal lifestyle Everyone they http://www.raybanzone.net/ soft Umbrella

Anonymous said...

Gгeetings! Very helpful аdvice within this аrticle!
It is the little chаnges that produсe the biggest сhangeѕ.

Thаnks fоr sharing!

mу рagе ... Http://Www.Delphi.Co.Kr/?Document_Srl=214861

Anonymous said...

Wow, this post is fastidious, my younger sister is
analyzing these things, therefore I am going to tell her.



my web page: Androsolve

Anonymous said...

In the beginning of the 11th Century the represents of Christianity is able to banned the
duel form einvigi and holmgangr as lawfully accepted means to solve a
dispute, and at the same time the berserkr and the beserksgangr was
made illegal. With the "information age" well under way, this is not surprising.
Even so, the registry may be corrupted, destroyed, clogged up, or infected causing Windows to be unable to read the files effectively.


My web page free pdf ebook download

Anonymous said...

Way cool! Some very valid points! I appreciate you penning
this article plus the rest of the website is also very good.



Feel free to surf to my web site ... pearl x

Anonymous said...

Although electronic cigarettes online emit smoke like water vapour, they do not contain tobacco.
Using an e-cig instead of smoking a stick of cigarette also
shows greater consideration for non-smokers.
This innovative device can keep food and beverages cool or warm in or out of the home.


Check out my homepage ... electronic cigarette reviews