"Oleg Tkachenko" <oleg@NO_!SPAM!_PLEASEtkachenko.com> wrote in message
news:%2****************@TK2MSFTNGP09.phx.gbl...
:
jo*******@genpt.com wrote:
:
: > I need to convert a text string ("Dewey & Cheatham & Howe") to an XML
encoded string ("Dewey & Cheatham & Howe"). I am not building an
XML document, I am just trying to convert a single string. I have looked at
the System.Xml namespace, but I can't quite find what I need.
XmlTextWriter.WriteString() does the type of encoding I need, but it writes
the string. I just want it to return the encoded string.
: >
: > Can someone tell me the class and method I need?
:
: Well, I'm not aware of any available method unfortunately. But in fact
: all you need is to replace & and < chars. They are only chars forbidden
: in XML in text, so double String.Replace or some regexp would suffice
: your needs:
:
: s.Replace("&", "&").Replace("<", "<")
The problem is a little more complicated than this, because it depends on
how the string is to be used.
For text content of an element, yes, just escaping ampersands and less-than
signs will do. For attribute content, escaping single and double quotes may
be necessary. For text in a CDATA section, a greater-than sign must be
escaped if it's preceded by two right brackets (otherwise the "]]>" will be
interpreted as the end of the CDATA section). See
http://www.w3.org/TR/REC-xml#syntax.
Why would anyone want to escape text for XML outside of the context of an
XML document, anyway? This smells like someone solving the wrong problem to
me.
Bob Rossney
rb*@well.com