Encode a String for Use in XML

L

Lamont Sanford

Given a string, what's the best way to transform it into an XML friendly
format?

For example, say I have a string like "hulio /<vonNostram <-!"

The less than ("<") and frontslash characters are confusing the third party
program that is receiving this string, since these characters have special
meanings in XML syntax. Is there a quick .NET function that will handle the
XMLizing of strings?

Thanks,

Lamont
 
J

Jeroen

Lamont,

Don't know if there's a specific _method_ to do this, but if you fill
the "InnerText" property of an System.Xml.XmlNode for example, then
you don't have to worry about escaping it (the setter does the
escaping for you).

Perhaps that helps a little.
 
J

Jon Skeet [C# MVP]

Given a string, what's the best way to transform it into an XML
friendly format?

That really depends on how you're creating the XML. There are usually
easy ways of asking the framework to do it as it creates the XML.

Jon
 
M

Martin Honnen

Lamont said:
Given a string, what's the best way to transform it into an XML friendly
format?

For example, say I have a string like "hulio /<vonNostram <-!"

The less than ("<") and frontslash characters are confusing the third party
program that is receiving this string, since these characters have special
meanings in XML syntax. Is there a quick .NET function that will handle the
XMLizing of strings?

Use XmlWriter to construct your XML, that way the necessary escaping of
'<' as '&lt;' is done.
You should construct the complete XML document using XmlWriter normally
but if you really want to escape only a string then that is possible
too, see the XmlEscape method in
<http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1562502&SiteID=1>
 
M

Michael S

Lamont Sanford said:
Given a string, what's the best way to transform it into an XML friendly
format?

For example, say I have a string like "hulio /<vonNostram <-!"

The less than ("<") and frontslash characters are confusing the third
party program that is receiving this string, since these characters have
special meanings in XML syntax. Is there a quick .NET function that will
handle the XMLizing of strings?

Thanks,

Lamont

In NET 3.5 there is a pretty neat solution:

string s = new XText("hulio /<vonNostram <-!").ToString();

- Michael S
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top