Use XML literals in C#

[XML literals]

Visual Basic lets you include XML literals directly in your code as in the following example.

Dim employees As XElement = 
      <employee firstname="Terry" lastname="Pratchett"/>
      <employee firstname="Glen" lastname="Cook"/>
      <employee firstname="Tom" lastname="Holt"/>

Unfortunately, C# doesn’t allow XML literals. Fortunately, you can fake them fairly easily. Invoke the XElement class’s Parse method passing it the XML text as a string beginning with the @ character. Strings that begin with @ can span multiple lines so you can make these sorts of strings look a lot like XML literals.

The only restriction is that the string cannot contain any double quotes because then C# would think the string had ended. Usually in XML text you can use single quotes instead of double quotes. If you really need to use double quotes, you can double them up as in “”.

When the program starts, it executes the following code. The XML literal is shown in blue.

    private void Form1_Load(object sender, EventArgs e)
        // Read the XElement.
        XElement xelement = XElement.Parse(
    <employee firstname=""Terry"" lastname=""Pratchett""/>
    <employee firstname='Glen' lastname='Cook'/>
    <employee firstname='Tom' lastname='Holt'/>

        // Display the nodes.
        foreach (XNode node in xelement.Nodes())

The code creates an XElement variable and sets it equal to the result returned by the XElement.Parse method. It passes the method the XML literal. Notice that it uses doubled double quotes to delimit the values for Terry Pratchett.

After it loads the XML text, the program loops through the XElement object’s nodes and displays their text values in the program’s ListBox.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in strings, XML and tagged , , , , , , , . Bookmark the permalink.