Skip to main content

Joys of XML Serialization

Love it or hate it, XML is everywhere and for data and objects, it can be extremely useful.

On one of my last projects, a colleague introduced me to the useful XSD2Code project, which creates a .Net object from an XSD. This made it easy for him to build a structure that could be compiled into code to ensure everyone followed the same structure. This is extremely valuable if someone gives you an XSD as a format to write to and you want to populate it using an object.

In a more recent project, we needed to share details from a component with another calling application via a web service. Enter XMLSerializer, the .Net equivalent of taking an object and dumping it into XML.

Dim s As XmlSerializer = New XmlSerializer(Object)
Dim w As New StringWriter()


s.Serialize(w, Object)
return w.tostring

Sounds great, right? It was for a short time, but as the object got bigger, it contained more collections and references to other objects. Eventually, the Serialize method took up 100% of CPU Usage and never finished. Of course, we couldn't find the problem right off the bat so it caused lots of grief.

(without going into too much detail showcasing my ignorance on all of the specifics, XMLSerializer uses reflection to identify all of the public properties of an object and then outputs them to an XML file - if the object has a lot of objects or collections within it, it can cause a huge drain on the whole process).

Certain posts call to use the BinaryFormatter instead - which is impossible to read but when you de-serialize it, you get the objects out at the other end.

Dim formatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()


Dim ms As New MemoryStream()


formatter.Serialize(ms, Me)


Dim sXML As String
sXML = System.Convert.ToBase64String(ms.ToArray())

But this makes the string illegible to any non-.Net applications, of which there are many - especially if you plan on building publicly accessible web services.

So I started to go through my initial object and blank out certain properties, so that the serialization would work.

What I didn't realize is I could simply tell the Serializer to ignore certain attributes. Enter the XMLIgnore attribute.

Instead of simply calling New XMLSerializer, I call a method that returns the Serializer but with certain attributes that tell it to ignore specific details.

Function GetSmartSerializer() as XMLSerializer
Dim xOver As New XmlAttributeOverrides()
Dim attrs As New XmlAttributes()


attrs = New XmlAttributes()
attrs.XmlIgnore = True
xOver.Add(GetType(ObjectClass), "MyBigCollectionThatNoOneNeedsToSee", attrs)


Dim xSer As New XmlSerializer(GetType(PRAM_Data.Session), xOver)
Return xSer

With the code above, when the application calls

Dim o as XMLSerializer = GetSmartSerializer()
Dim w As New StringWriter()


s.Serialize(w, Object)
return w.tostring

It now excludes the property "MyBigCollectionThatNoOneNeedsToSee" from the XML.

More details can be found here:
XmlAttributes.XmlIgnore Property (System.Xml.Serialization)

I'm curious though - has anyone else encountered this limitation of the XMLSerializer? What solution have you used?

Comments

Unknown said…
This comment has been removed by the author.
Unknown said…
Have you considered using the json serializer? I'm starting to switch to json for large data feeds, since they typically require about half the bandwidth of an equivalent xml feed.

A few years back I was doing some serialization with hybernate and castor in Java. When I traced the bottleneck to it's source, I found that over 90% of the time was spent expanding the string builder. The performance was so bad that it threatened to derail the whole project. I ended up passing in a stringbuilder with a preset capacity so that it would not need to be continually resized.

That being said, you might see a similar result in C# by initializing the StringWriter as follows:

StringWriter w = new StringWriter(new StringBuilder(myExpectedCapacity));
Andrew MacNeill said…
Hi Brian,

The only issue right now is that I don't control the other applications accessing the data so they are expecting XML.

However, I'll add JSON as an alternate export and see if it improves performance.

Great idea - thanks!

Popular posts from this blog

Blogs and RSS come to Microsoft.com

MS has just introduced their portal and it's pretty comprehensive. Nothing quite like learning that some people use AIM instead of MSN messenger, or that there really may be a need for supporting 4 monitors ( Cyrus Complains ) However, it's really a great sign that MS is serious about supporting the blogging community which seems to have um, exploded in size in the past year. Blogs and RSS come to Microsoft.com

Elevating Project Specifications with Three Insightful ChatGPT Prompts

For developers and testers, ChatGPT, the freely accessible tool from OpenAI, is game-changing. If you want to learn a new programming language, ask for samples or have it convert your existing code. This can be done in Visual Studio Code (using GitHub CoPilot) or directly in the ChatGPT app or web site.  If you’re a tester, ChatGPT can write a test spec or actual test code (if you use Jest or Cypress) based on existing code, copied and pasted into the input area. But ChatGPT can be of huge value for analysts (whether system or business) who need to validate their needs. There’s often a disconnect between developers and analysts. Analysts complain that developers don’t build what they asked for or ask too many questions. Developers complain that analysts haven’t thought of obvious things. In these situations, ChatGPT can be a great intermediary. At its worst, it forces you to think about and then discount obvious issues. At best, it clarifies the needs into documented requirements. ...

Programmers vs. Developers vs. Architects

I received an email this morning from Brandon Savage 's newsletter. Brandon's a PHP guru (works at Mozilla) but his newsletter and books have some great overall perspectives for developers of all languages. However, this last one (What's the difference between developers and architects?) kind of rubs me the wrong way. Either that, or I've just missed the natural inflation of job descriptions. (maybe, it's like the change in terminology between Garbage man and Waste Engineer or Secretary and Office Administrator) So maybe it's just me - but I think there's still a big difference between Programmer, Developer and then of course, architect. The key thing here is that every role has a different perspective and every one of those perspectives has value. The original MSF create roles like Product Manager, Program Manager, Developer, Tester, etc - so every concept may pigeon hole people into different roles. But the statements Brandon makes are often distinction...