Chris Eargle

Life Student of the Kodefu Arts

XML Nugget of Joy

by chris 27. June 2007 12:22

I needed to stick a small piece of xml into a database field, sans any wordy junk that tends to inhabit xml. My requirement has length restrictions, so I wanted to keep the character count down. Basically, I needed something like this:

<candy>

<chocolate>yum</chocolate>

<caramel>creamy</caramel>

<nougat>whatisthis</nougat>

</candy>

Pretty simple, huh? My first inclination was to use XmlDocument and start adding nodes, but that tact turned out to be cumbersome and was too procedural for my taste. So, I turned to making a small data holding class so I could serialize it!

[Serializable]
[
XmlRoot("candy")]
public class
CandyData
{

string _chocolate;
string _caramel;
string _nougat;

[XmlElement("chocolate")]
public string Chocolate
{

get { return _chocolate; }
set { _chocolate = value; }

}

[XmlElement("caramel")]
public string Caramel
{

get { return _caramel; }
set { _caramel = value; }

}

[XmlElement("nougat")]
public string Nougat
{

get { return _nougat; }
set { _nougat = value; }

}

}

That's pretty straight-forward as well. The problem came when I serialized the class and look at what was being returned: declarations and namespaces. It turns out that special steps are required to strip out the xml declaration from the top, <?xml version="1.0" encoding="utf-16"?>, and the namespace, xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd=http://www.w3.org/2001/XMLSchema, from the root element.

Instead of writing up a gigantic article describing every step I took to figure this out (google and msdn), how about I give out the code that does it and illustrates what's required!

public static class XmlNugget

{

/// <summary>
///
Serializes the specified obj into simple xml text.
/// </summary>
///
<param name="obj">The obj to serialize</param>
///
<returns>A simple xml nugget of joy.</returns>
public static string Serialize(Object obj)
{


XmlSerializer serializer = new XmlSerializer(obj.GetType());
StringBuilder sb = new StringBuilder();

//This will clear out default namespaces
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add(
String.Empty, String.Empty);

//This is needed to get rid of the <?xml...>
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;

XmlWriter xmlWriter = XmlTextWriter.Create(sb, settings);
serializer.Serialize(xmlWriter, obj, ns);


return sb.ToString();

}


}

This is a simple static class that takes an object and spits out xml in a string. The xml is a simple structure... no namespacing or anything unless you defined it in your class attributes. In my opinion, this helper class is preferable to typing all that junk out everytime you need to serialize an object into xml and then read it into a string.

If you're looking for a more professional name, I recommend SimpleXmlText. Unfortunately, sugar cravings do weird things to a programmer's mind. That's what I get for switching to black coffee with no sugar.

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

xml, serialization, c#

Kodefu

E-mail | Kick it! | DZone it! | del.icio.us
Permalink | Comments (2) | Post RSSRSS comment feed

Powered by BlogEngine.NET 1.3.1.0
Theme by Mads Kristensen

About the author

Chris Eargle Chris Eargle
Enterprise .NET developer in Columbia, SC.

E-mail me Send mail

Pages

  • Presentations

Twitter Updates

    Recent comments

    • Dev InTENsity (3)
      Chris Eargle wrote: Thanks for attending my presentations, Seth! In… [More]
    • Set Operations in MSBuild (1)
      FreeToDev wrote: Very nice post. Makes me wonder why I wrote tasks … [More]
    • Dev InTENsity (3)
      Seth Richards wrote: I saw both your C# 3.0 (I came up with the 'why ex… [More]
    • Dev InTENsity (3)
      Scott Ames wrote: I went to your presentation in Walthan for Code Ca… [More]
    • Generics Don't Make Me Sad (1)
      Matt Sheppard wrote: Cheers, I can't remember if I was aware of either… [More]
    • C# 3.0 Presentation (1)
      vijay wrote: Good post Thanks, Vijay [More]
    • Format Solution (4)
      Joe wrote: I added a couple of lines to FormatProjectItem() t… [More]
    • Sessions Galore (1)
      Lou wrote: I'll have to get you down here soon - I'll e-mail … [More]
    • Redeemed (3)
      Fred Beiderbecke wrote: It wasn't you, it was some of the others in the ro… [More]
    • South Florida Code Camp (1)
      Jason Meridth wrote: You've mentioned the only latest difference betwee… [More]

    Archive

    • 2008
      • November (3)
      • October (7)
      • September (8)
      • August (5)
      • July (1)
      • June (1)
      • April (4)
      • March (1)
      • February (4)
      • January (5)
    • 2007
      • December (5)
      • November (1)
      • October (6)
      • September (3)
      • August (1)
      • June (1)

    Tags

    • activex
    • addin
    • ado.net data services
    • ajax
    • architecture
    • astoria
    • azure
    • beta
    • bug
    • c#
    • code camp
    • com
    • consolas
    • continuous integration
    • conversion
    • ctp
    • database
    • deployment
    • design
    • design principles
    • download
    • ebook
    • entity
    • entlib
    • environment variables
    • expression blend
    • fail
    • font
    • framework
    • gadget
    • generics
    • grid
    • guidelines
    • icon
    • interfaces
    • jacksonville
    • lamdba
    • linq
    • linqtosql
    • list
    • live mesh
    • macro
    • mobile
    • msbuild
    • msdn
    • msi
    • mvc
    • powertoy
    • preview
    • properties
    • ray ozzie
    • refactoring
    • regasm
    • russ fustino
    • security
    • serialization
    • silverlight
    • snippet
    • source code
    • sql server
    • sqlmetal
    • starter kit
    • stream
    • string
    • trial
    • usability
    • ux
    • vbscript
    • vista
    • visual studio
    • vs2008
    • wcf
    • web
    • winforms
    • wpf
    • xml

    Categories

    • RSS feed for Bleeding EdgeBleeding Edge (5)
    • RSS feed for CEDGCEDG (2)
    • RSS feed for GeneralGeneral (1)
    • RSS feed for KodefuKodefu (19)
    • RSS feed for Path NotesPath Notes (7)
    • RSS feed for PresentationPresentation (5)
    • RSS feed for TechniquesTechniques (2)
    • RSS feed for TrainingTraining (5)
    • RSS feed for WeaponsWeapons (4)
    • RSS feed for ZenZen (5)

    Archive

    Blogroll

    • RSS feed for Structure Too BigStructure Too Big
      • Should you buy an exten...
      • WorldMaps Update
      • MSDN Roadshow -- coming...
    • RSS feed for Chris CraftChris Craft
      • Raleigh Code Camp Fall...
      • [PDANUG] Event Reminder...
      • MSDN Southern Fried Roa...
    Download OPML file OPML

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2008

    Sign in