Click here to Skip to main content
Click here to Skip to main content

TRICK: Xml Literals for C#

, 4 Sep 2010
Rate this:
Please Sign up or sign in to vote.
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.

License

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

About the Author

Jaime Olivares
Architect Freelance (jaimeolivares.com)
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 C# 2013 and TFS.
Can be reached at http://www.jaimeolivares.com
Follow on   LinkedIn

Comments and Discussions

 
GeneralMy vote of 1 Pinmemberpdamp20-Feb-13 4:43 
GeneralRe: My vote of 1 PinmemberJaime Olivares20-Feb-13 4:53 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 4 Sep 2010
Article Copyright 2010 by Jaime Olivares
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid