XmlUtility?

  • Thread starter Thread starter Anders K. Olsen
  • Start date Start date
A

Anders K. Olsen

Hello Group

I need to XML encode a string.

Is there something like System.Web.HttpUtility.UrlEncode(string) but just
for XML?

I need something that does the same as XmlTextWriter.writeString(), but I
would prefere to avoid all the overhead in creating the XmlTextWriter
itself.

Regards

Anders Olsen
 
Anders said:
Hello Group

I need to XML encode a string.

Is there something like System.Web.HttpUtility.UrlEncode(string) but
just for XML?

I need something that does the same as XmlTextWriter.writeString(),
but I would prefere to avoid all the overhead in creating the
XmlTextWriter itself.

Isn't that a typical case of premature optimization? What's wrong with
XmlTextWriter?
 
Joerg Jooss said:
Isn't that a typical case of premature optimization? What's wrong with
XmlTextWriter?

I only need one string converted. I don't need an entire XML document:

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlTextWriter xtw = new XmlTextWriter(sw);
xtw.WriteString(text);
xtw.Flush();
xtw.Close();
return sb.ToString();

compared to

return System.Web.HttpUtility.UrlEncode(text);

Of course, I don't know what happends in the UrlEncode method. Perhaps it
also uses StringBuilders and StringWriters and other stuff. But then neither
do I know what happends in XmlTextWriter.WriteString.

With UrlEncode, Microsoft may optimize the method in a future version of
..Net. With XmlTextWriter, they may optimize the WriteString method, but I
will still create the StringBuilder and StringWriter objects.

And also, it is just nicer to look at a one-liner that does the job :-)

Regards
Anders
 
Anders said:
I only need one string converted. I don't need an entire XML document:

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlTextWriter xtw = new XmlTextWriter(sw);
xtw.WriteString(text);
xtw.Flush();
xtw.Close();
return sb.ToString();

compared to

return System.Web.HttpUtility.UrlEncode(text);

Of course, I don't know what happends in the UrlEncode method.
Perhaps it also uses StringBuilders and StringWriters and other
stuff. But then neither do I know what happends in
XmlTextWriter.WriteString.

With UrlEncode, Microsoft may optimize the method in a future version
of .Net. With XmlTextWriter, they may optimize the WriteString
method, but I will still create the StringBuilder and StringWriter
objects.

That's what I meant with premature optimization. I assume you're not
writing an application whose sole purpose is XML encoding at 100%
processor utilization ;-)

Trust the framework, and add the things that you're missing, building
them on top of the framework.
And also, it is just nicer to look at a one-liner that does the job
:-)

I totally agree to that. But hey, you've got all the code to do that. A
helper class, a static method and off you go.


Cheers,
 
Back
Top