RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » XML
Language: .NET
Expertise: Intermediate
Jun 5, 2007

Special Characters in XML Element and Attribute Names

When creating XML files, sometimes there are fields (elements/attributes) where you need to use special characters like space, &, <, etc. However, according to the XML specification, these are invalid.

.NET provides the EncodeName and DecodeName methods in the XMLConvert class for just this purpose. These methods encode and decode the special characters and convert them to valid XML values.

For instance:

//To create an element with the name "Test Level"
xmlTextWriter.WriteElementString("Test Level", "600");
//would throw an error on trying to view it

//use EncodeName() instead
xmlTextWriter.WriteElementString(XmlConvert.EncodeName("Test Level"), "600");

Note: Always use XmlConvert.

Srinath MS
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date