tags:

views:

267

answers:

3

I am creating several XmlElements used in a larger XML Document.

XmlElement thisElement = xmlSearchParameters.CreateElement("value");
thisElement.InnerXml = this.searchParameters[key];

This works well for most instances, but if the value of searchParameters[key] happens to include an & symbol, I get one of the two following errors:

Unexpected end of file has occurred. Line 1, position 1. - if value is ONLY &

An error occurred while parsing EntityName. Line 1, position 7. - if value contains & mixed with other text.

What is the prefered way of including & and any other special symbols in an XmlElement? I suspect there must be a better way than just replacing & with something else (some sort of XmlFormat method???).

Thanks!

+1  A: 

SecurityElement.Escape will replace the less than, greater than, quote, apostrophe, and ampersand symbols, which is probably all you need.

Mark Rushakoff
+5  A: 

Why do you use InnerXml in the first place? It's supposed to be used if you have some valid markup in unparsed string form, and want to insert it there. For plain text, use InnerText:

thisElement.InnerText = this.searchParameters[key];
Pavel Minaev
Thanks for the tip. I haven't worked with XmlElement much in the past and this is just how the code was setup when I started working on it. Changing to use InnerText solves my problem.
Kris
+3  A: 

If you use InnerXml you have to guarantee that text value is valid xml. Use InnerText property instead of InnerXml.

Lloyd