Click here to Skip to main content
15,112,869 members
Articles / Programming Languages / XML
Posted 31 May 2010

Tagged as


3 bookmarked

TRICK: Xml Literals for C#

Rate me:
Please Sign up or sign in to vote.
3.89/5 (5 votes)
4 Sep 2010CPOL
Workaround to mimic'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 -->
            <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'/>
            <magazineName>&quot;MSDN Magazine&quot;</magazineName>
            <magazineName>&quot;Code Magazine&quot;</magazineName>

Whenever the quote is needed you can use the &quot entity, and for apostrophes use the &apos entity.


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


About the Author

Jaime Olivares
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 5:02
Memberpm823-Apr-14 5:02 
GeneralMy vote of 1 Pin
pdamp20-Feb-13 5:43
Memberpdamp20-Feb-13 5:43 
GeneralRe: My vote of 1 Pin
Jaime Olivares20-Feb-13 5:53
MemberJaime Olivares20-Feb-13 5:53 
QuestionXML Literals are queryable. Pin
s_p_s2-Feb-13 9:21
Members_p_s2-Feb-13 9:21 
AnswerRe: XML Literals are queryable. Pin
Jaime Olivares20-Feb-13 5:55
MemberJaime Olivares20-Feb-13 5: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.