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() insteadxmlTextWriter.WriteElementString(XmlConvert.EncodeName("Test Level"), "600");

Note: Always use XmlConvert.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: