65.9K
CodeProject is changing. Read more.
Home

TRICK: Xml Literals for C#

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.89/5 (5 votes)

May 31, 2010

CPOL
viewsIcon

30424

Workaround to mimic VB.net's Xml Literals in C#

Please have a glance to jpaulino's article Xml Literals[^] Unfortunately, this useful feature doesn't work for C#. But there is a workaround to mimic this functionality. It combines 2 characteristics: - Well formed xml documents can use quotes or apostrophes for attributes. - C# string literales can have newlines when using the verbatim mode (leading @). So, we can create a LINQ XDocument by passing the xml string to the Parse method. Unique condition is to be sure that attributes are not enclosed between quotes, but between apostrophes, like the following example:
using System.Xml.Linq;

XDocument bookList = XDocument.Parse(
    @"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
    <!-- List of books and magazines -->
    <library>
        <books>
            <book name='The Hunger&apos;s Games' author='Suzanne Doe'/>
            <book name='Breaking Dawn' author='Stephenie Meyer'/>
            <book name='The Last Song' author='Nicholas Sparks'/>
        </books>
        <magazine>
            <magazineName>&quot;MSDN Magazine&quot;</magazineName>
            <magazineName>&quot;Code Magazine&quot;</magazineName>
        </magazine>
    </library>");
Whenever the quote is needed you can use the &quot entity, and for apostrophes use the &apos entity.