Verify XML Names Using C#

The XML specification does not allow some characters to be a part of valid XML names. For example, you cannot use a space as a part of an XML name (tag). So, if you create an element with name "Author Name", it will be invalid. But the XML classes are smart enough to handle it for you, and will add a code (as in "_x0020_") to the name and when you read it back, it removes this code from the name. For example, the name Author Name is encoded as Author_x0020_Name. 

When dealing with extensive XML operations, you may manually want to handle XML name conversions. This is where the XmlXonvert class is used. It provides two methods, "XmlConvert.EncodeName" and "XmlConvert.DecodeName" that encode and decode, respectively, an invalid name to a valid XML name.

The following code snippet creates a name with a space in it. 

string authorName = XmlConvert.EncodeName("Author Name");
Console.WriteLine("Encoded name: " + authorName);
Console.WriteLine("Decoded name: " + XmlConvert.DecodeName(authorName));
Console.ReadKey(); 

If you run this code, you will see the method XmlConvert.EncodeName has replaced a space character with the code _x0020_ that makes it a valid name and the XmlConvert.DecodeName method decodes it back to the original name.

 XmlConvert-VerifyName.png

The XmlConvert class also has a method, VerifyName that verifies that a name is a valid XML name according to the W3C Extended Markup Language recommendation. 

Here is a complete example that verifies a name and if the name is not a valid XML name then it decodes it before writing to the document. 

static void Main(string[] args)
{
    using (XmlTextWriter writer = new XmlTextWriter("Books.xml", null))
    {
        string author = "Author Name";

        try
        {
            // Write root node
            writer.WriteStartElement("Authors"); 

            // verify author name is a valid XML name?
            writer.WriteStartElement(XmlConvert.VerifyName(author));

        }
        catch (XmlException e)
        {
            // Get error here
            Console.WriteLine(e.Message + ": {0}", author);
            writer.WriteStartElement(XmlConvert.EncodeName(author));
        }
        writer.WriteString("Mahesh Chand");
        writer.WriteEndElement();
        // End root node
        writer.WriteEndElement();
    }
    Console.ReadKey();
}

In the code above, the XmlConvert.VerifyName method verifies a name and if the name is not valid then it encodes it before writing it as an element. 

You will see this message when you run this code. 

XmlConvert-EncodeName.png

Note: Don't forget to add a "using System.XML" for that namespace in your code, as in:

using System.Xml;


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.