Click here to Skip to main content
15,867,488 members
Articles / Programming Languages / XML
Tip/Trick

TRICK: Xml Literals for C#

Rate me:
Please Sign up or sign in to vote.
3.89/5 (5 votes)
4 Sep 2010CPOL 29.4K   3   5
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)


Written By
Architect
Peru Peru


Computer Electronics professional, Software Architect and senior Windows C++ and C# developer with experience in many other programming languages, platforms and application areas including communications, simulation systems, PACS/DICOM (radiology), GIS, 3D graphics and HTML5-based web applications.
Currently intensively working with Visual Studio and TFS.

Comments and Discussions

 
QuestionAn example with a string mixed with textbox values Pin
pm823-Apr-14 4:02
pm823-Apr-14 4:02 
GeneralMy vote of 1 Pin
pdamp20-Feb-13 4:43
pdamp20-Feb-13 4:43 
GeneralRe: My vote of 1 Pin
Jaime Olivares20-Feb-13 4:53
Jaime Olivares20-Feb-13 4:53 
QuestionXML Literals are queryable. Pin
s_p_s2-Feb-13 8:21
s_p_s2-Feb-13 8:21 
AnswerRe: XML Literals are queryable. Pin
Jaime Olivares20-Feb-13 4:55
Jaime Olivares20-Feb-13 4:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.