There are often occasions when you need to use special characters and have them represented as valid XML element names.
As we already know, characters such as blank spaces, &, <, > etc. cannot be represented as valid XML element or attribute
names just the way they are. They need to be encoded or escaped into characters that are accepted as valid XML.
The XmlConvert class provides an easy way to do this through the EncodeName() and DecodeName() methods.
Let's take a look at an example:
using System;
using System.Xml;
class Product
{
[STAThread]
static void Main(string[] args)
{
XmlTextWriter xmlTextWriter = null;
try
{
xmlTextWriter = new XmlTextWriter(@"c:\products.xml", null);
xmlTextWriter.Formatting = Formatting.Indented;
xmlTextWriter.WriteStartDocument();
xmlTextWriter.WriteStartElement("Products");
xmlTextWriter.WriteStartElement("Product");
xmlTextWriter.WriteAttributeString("SKU", "123");
xmlTextWriter.WriteAttributeString("Product", "ChocoRaisin Supreme");
xmlTextWriter.WriteElementString("Redorder Level", "200");
xmlTextWriter.WriteElementString("Notifications & Alerts", "Reorder@AcmeIcecreams.com");
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteEndDocument();
}
finally
{
if(xmlTextWriter != null)
{
xmlTextWriter.Flush();
xmlTextWriter.Close();
}
}
}
}
Notice that the Reorder Level and the Notifications & Alerts element names contain invalid XML characters (space and ampersand
respectively) that causes malformed XML to be written to the Products.xml file.
As shown below, to correct this, use the XmlConvert.EncodeName() to encode such special characters into XML friendly equivalents:
xmlTextWriter.WriteElementString(XmlConvert.EncodeName("Redorder Level"), "200");
xmlTextWriter.WriteElementString(XmlConvert.EncodeName("Notifications & Alerts"), "Reorder@AcmeIcecreams.com");
This causes the following encoded XML to be written to Products.xml:
Conversely, use XmlConvert.DecodeName() to convert the encoded characters back to their original form.