Home > View Post

XmlWriter or string concatenation

Whilst we're on the subject of coding practice, Jeff Atwood recently posted his thoughts on When Object-Oriented Rendering is Too Much.

He discusses how it seems overkill to use the XmlWriter to generate a piece of Xml like so:

<status code="1" />
<usergroup id="usr" />

Commenters were quick to point out that his string concatenation solution would fall at the slightest encoding hurdle (for example, if the id attribute was to contain a > or a ").

Jeff was quick to enhance his code in the comments with an XmlEncode() method that would take care of that problem but this was a proving point for me: when people string Xml together they forget to encode the values.

Sure it's easy to fix but that depends when the problem is found (after release?). If you use the tools you remove any chance of this happening and you get guaranteed wellformedness. Isn't that worth a few extra lines of code?

On the subject of the concatenation technique and its vulnerability to errors, Jeff went on to note that:

"I had to experiment quite a bit with the Write commands to get the output XML to match the requirements. Was that error prone? You bet it was."

But these errors were down to his inexperience in using the XmlWriter, which is no excuse never to use something. Maybe if we used it a little more often then we wouldn't have this trouble?

My biggest question is with the example though. How often do we have to generate a piece of Xml as simple as this?

string s =
@"<status code=""{0}"" />
    <usergroup id=""{1}"" />
return String.Format(s, "1", "usr");

It's much more likely that we'd have to do this (or worse)...

string s = string.Format(
@"<status code=""{0}"" />
, 1);
foreach (UserGroup group in Groups)
    s+= string.Format(
    @"<usergroup id=""{0}"" />", group.Id);

s+= "</data>";
return s;

... which makes me want to run for the hills. I think this may have been Jeff's point, in that it's OK not to use the XmlWriter for a simple example, though it got lost in the ensuing debate.

Personally, I would favour the consistency of approach and use the XmlWriter in both cases. I'd be getting some practice in at the same time and protection from some common slip-ups thrown into the bargain too.

Tags: .NET

Josh Post By Josh Twist
1:16 AM
27 Jun 2006

» Next Post: How to change working folder in TFS
« Previous Post: Trying too hard too soon

Comments are closed for this post.

© 2005 - 2021 Josh Twist - All Rights Reserved.