Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

TRICK: Xml Literals for C#

3.89/5 (5 votes)
4 Sep 2010CPOL 30.4K  
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:

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)