Click here to Skip to main content
11,718,289 members (83,076 online)
Click here to Skip to main content

XML Literals

, 12 Apr 2010 CPOL 53.2K 72
Rate this:
Please Sign up or sign in to vote.
XML Literals allow you to use XML syntax in your code. It’s easy to work with XML files this way, since you have that Tags in the code, but it’s also quicker to access information rather than the traditional methods.

This is an English version of some articles I posted a while ago in my blog. XML Literals are a great way to handle XML files and the community doesn't use it as much as it should.

xmlliterals0.jpg

Introduction

XML Literals allow you to use XML syntax in your code. It’s easy to work with XML files this way, since you have that Tag in the code, but it’s also quicker to access information rather than the traditional methods using XmlDocument and XmlElement. It’s available in the namespace System.Xml.Linq, since the .NET Framework 3.5/Visual Studio 2008 (for Visual Basic Only) supports most of the Extensible Markup Language (XML) 1.0 specification, and together with Lambda Expressions and/or LINQ, gives you a better experience with XML files. It’s also available in the intellisense, and it automatically indents the code.

XML Literals

NOTE: Most of the examples use Option Infer On but you can declare the correct variables data type.

The basic concept looks like this:

Dim msg = <msg> 
              This is a test! 
              This is a test! 
          </msg>

This will show you a MessageBox, preserving the spaces, tabs and page breaks. Notice that it doesn't need the line continuation character “_” (which will not even be necessary in Visual Studio 2010 for most of the code).

You can create your XML file in runtime mode. Here’s an example of how to achieve that:

Dim bookList = _ 
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
    <!-- List of books and magazines --> 
    <library> 
        <books> 
            <book name="The Hunger Games " author="Suzanne Collins"/> 
            <book name="Breaking Dawn" author="Stephenie Meyer"/> 
            <book name="The Last Song" author="Nicholas Sparks"/> 
        </books>

The variable bookList is now an XDocument that you can work as an XML file. To save the file on the disk, you just need to use the Save() method:

bookList.Save("c:\library.xml")

Read Information

The previous example generates an easy XML file and saves it to disk. To load the file and handle it, you can use the Load() event. This will load the file and show the magazine name, using the Descendants property, which allow access to descendant nodes by name from an XElement or XDocument object:

Dim xmlFile = XDocument.Load("c:\library.xml") 
Debug.WriteLine(xmlFile...<magazineName>.Value)

This will show in the Immediate Window “MSDN Magazine” because it’s the first name that it found. We can also get the second magazine (in this case), using Lambda Expressions:

Dim xmlFile = XDocument.Load("c:\library.xml") 
Debug.WriteLine(xmlFile...<magazineName>.Where(Function(f) _ 
                               f.Value = "Code Magazine").Value)

This is for “regular” node elements but if you need to show attributes, then you should use the following syntax:

Dim xmlFile = XDocument.Load("c:\library.xml") 
Debug.WriteLine(xmlFile...<book>.@author) 

And for the Lambda Expression to filter for a specific value (this will search on the book name and show the author name):

Dim xmlFile = XDocument.Load("c:\library.xml") 
Debug.WriteLine(xmlFile...<book>.Where(Function(f) _ 
                                 f.@name = "Breaking Dawn").@author)

List Information

You have several ways to show information, looping on the values, using LINQ to XML or Lambda Expressions. You can list all the magazines this way:

For Each m In From element In bookList.<library>.<magazine>.<magazineName> 
   Debug.WriteLine(m.Value) 
Next 

You can also use the Descendants property and significantly simplify the code:

For Each m In From element In bookList...<magazineName> 
    Debug.WriteLine(m.Value) 
Next 

To show the book names you can use the same method, but since you now deal with attributes, you use the “@” to define that you want the attribute, plus the attribute name.

For Each book In From element In bookList...<book> 
    Debug.WriteLine("Book: " & book.@name.ToString) 
    Debug.WriteLine("Author: " & book.@author.ToString) 
    ' Separation line 
    Debug.WriteLine(New String("-"c, 40)) 
Next 

But you can also filter the information before showing it. This example uses LINQ to XML to check all of the books that have a name containing the keyword “Song”.

' Using LINQ to XML to filter the information 
Dim bookSearch = From b In bookList...<book> _ 
         Where b.@name.ToString.Contains("Song") _ 
         Select b.@name, b.@author 

' Show the results 
For Each book In From element In bookSearch 
    Debug.WriteLine("Book: " & book.name) 
    Debug.WriteLine("Author: " & book.author)     

    ' Separation line 
    Debug.WriteLine(New String("-"c, 40)) 
Next 

Embedded Expressions

Embedded expressions are expressions that you can use in the XML code, using the tags <%= expression %>, like it’s available in ASP.NET. You can use them to build or modify the XML file and that makes it really easy to create a file from a DataTable, List(Of T), Dictionary, etc.

Here’s a very straight forward example, using a Func() delegate (Lambda Expression) that adds two values:

Dim f As Func(Of Integer, Integer, Integer) = Function(x, y) x + y 

Dim example = _ 
    <test> 
        <value><%= f(125, 125).ToString() %></value > 
    </test>

The result will be:

<test> 
     <value>250</value> 
</test> 

If you have another datasource, like a List(Of T), you can list all the values, using embedded expressions, to an XML file:

' Creates a list with some book names  
Dim bookList As New List(Of String) 
bookList.AddRange(New String() {"The Hunger Games", "Breaking Dawn", "The Last Song"}) 

' Creates the XML e saves it to disk 
Dim newBookList1 = _ 
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
    <library> 
        <books> 
            <%= From b In bookList Select <book><%= b %></book> %> 
        </books> 
    </library> 

newBookList1.Save("c:\result.xml")

This will be the result:

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
  <library>
     <books>
           <book>The Hunger Games</book>
           <book>Breaking Dawn</book>
           <book>The Last Song</book>
     </books>
</library>

Another example of using embedded expressions is using a DataTable. In this case, it will create an XML file with the attributes “name” and “author”:

' For this example is created a DataTable manually but 
' could be the result of a SQL query or stored procedure 
Dim dt As New DataTable("Books") 
dt.Columns.Add("Book", GetType(String)) 
dt.Columns.Add("Author", GetType(String)) 
dt.Rows.Add("The Hunger Games", "Suzanne Collins") 
dt.Rows.Add("Breaking Dawn", "Stephenie Meyer") 
dt.Rows.Add("The Last Song", "Nicholas Sparks") 
Dim ds As New DataSet 
ds.Tables.Add(dt) 

' Creates the XML e with two attributes: "name" and "author"  
Dim newBookList2 = _ 
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
   <!-- my book list --> 
   <library> 
       <books> 
           <%= From b In ds.Tables("Books") Select _ 
               <book name=<%= b.Item("Book") %> 
                   author=<%= b.Item("Author") %>/> %> 
       </books> 
   </library> 

' Saves it to disk 
newBookList2.Save("c:\library.xml") 

This will be the result:

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<library>
        <books>
            <book name=" The Hunger Games" author="Suzanne Collins" />
            <book name=" Breaking Dawn" author="Stephanie Meyer" />
            <book name=" The Last Song" author="Nicholas Sparks" />
        </books>
</library>

Modify Nodes

To modify any information in an XML file, using XML Literals, you just need to read the file, change the value and then save it to disk.

Here’s an example:

Dim xmlFile = XDocument.Load("c:\library.xml") 
xmlFile...<magazineName>.Value = "New Value" 
xmlFile.Save("c:\library.xml")

But using this approach, only the first value that is found will be changed. If you need to change a specific value, like you normally do, you need to filter the information first to indicate what value to change:

Dim xmlFile = XDocument.Load("c:\library.xml") 
Dim element = xmlFile.<library>.<books>.<book>.Where(Function(f) _ 
                             f.@name = "The Last Song") 
element.@author = "Jorge Paulino" 
xmlFile.Save("c:\library.xml")

This will change the name of the author for the book “The Last Song”, from “Nicholas Sparks” to “Jorge Paulino” (that was nice!). But once again, using the Descendants property saves you some code:

Dim xmlFile = XDocument.Load("c:\library.xml") 
xmlFile...<book>.Where(Function(f) _ 
                f.@name = "The Last Song").@author = "Jorge Paulino" 
xmlFile.Save("c:\library.xml") 

Inserting Nodes

To insert a new node into the XML file, you first need to build the new element (XElement) and then add it to the right position. We can do that in two ways:

Dim xmlFile = XDocument.Load("c:\library.xml") 
Dim element = New XElement("book", _ 
                    New XAttribute("name", "XML Literals"), _ 
                    New XAttribute("author", "Jorge Paulino")) 
Dim parent = xmlFile...<books>.FirstOrDefault() 
parent.Add(element) 
xmlFile.Save("c:\library.xml")

Or, the easy way:

Dim xmlFile = XDocument.Load("c:\library.xml") 
Dim element = <book name="XML Literals" author="Jorge Paulino"/> 
Dim parent = xmlFile...<books>.FirstOrDefault() 
parent.Add(element) 
xmlFile.Save("c:\library.xml")

In this example, we can change the values of the attributes dynamically, using embedded expressions like we saw before.

Deleting Nodes

Deleting a node is very similar to the modification method. You can remove all the nodes:

Dim xmlFile = XDocument.Load("c:\library.xml") 
xmlFile...<magazineName>.Remove() 
xmlFile.Save("c:\library.xml")

Or remove a specific node:

Dim xmlFile = XDocument.Load("c:\library.xml") 
xmlFile...<book>.Where(Function(f) f.@author = "Suzanne Collins").Remove() 
xmlFile.Save("c:\library.xml")

Finally Example (web)

You can also use XML Literals to read information from the web, like RSS. This example reads my personal blog RSS and filters by the “VB.NET” category (that is defined by the tags). This show how powerful and easy it is to work with XML Literals.

Dim xmlFile = XDocument.Load("http://feeds.feedburner.com/vbtuga")</a />

And the console result:

xmlliterals2.jpg

Conclusion

XML literals provide several methods to work with XML files. Today, you have XML files for everything (reports, configurations, data storage, RSS, etc.) and it’s so important to handle it right, fast and in a easy way.

I hope this article helps you to become better with XML Literals, and use them more!

License

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

Share

About the Author

jpaulino
Software Developer
Portugal Portugal
Jorge Paulino
Microsoft Visual Basic MVP
Portuguese Software Developer
VB.NET, ASP.NET, VBA, SQL
http://vbtuga.blogspot.com/

http://twitter.com/vbtuga

You may also be interested in...

Comments and Discussions

 
QuestionAwesome! Pin
Member 13480306-Feb-13 1:32
memberMember 13480306-Feb-13 1:32 
GeneralMy vote of 1 Pin
GangadharaRao1-Feb-13 1:44
memberGangadharaRao1-Feb-13 1:44 
GeneralMy vote of 5 Pin
Savalia Manoj M2-Jan-13 17:52
memberSavalia Manoj M2-Jan-13 17:52 
Good work..!!
GeneralMy vote of 5 Pin
rctaubert29-Mar-12 8:57
memberrctaubert29-Mar-12 8:57 
QuestionReal World xml Files Pin
rctaubert29-Mar-12 7:23
memberrctaubert29-Mar-12 7:23 
AnswerRe: Real World xml Files Pin
jpaulino29-Mar-12 7:38
memberjpaulino29-Mar-12 7:38 
GeneralRe: Real World xml Files Pin
rctaubert29-Mar-12 8:49
memberrctaubert29-Mar-12 8:49 
GeneralRe: Real World xml Files Pin
rctaubert29-Mar-12 8:57
memberrctaubert29-Mar-12 8:57 
GeneralRe: Real World xml Files Pin
jpaulino29-Mar-12 9:48
memberjpaulino29-Mar-12 9:48 
Generalthats what happened with me Pin
Xmen W.K.30-Dec-10 15:24
memberXmen W.K.30-Dec-10 15:24 
GeneralCongrats and small question Pin
zimvbcoder3-Jun-10 1:49
memberzimvbcoder3-Jun-10 1:49 
GeneralRe: Congrats and small question Pin
jpaulino3-Jun-10 2:00
memberjpaulino3-Jun-10 2:00 
GeneralRe: Congrats and small question Pin
zimvbcoder3-Jun-10 2:13
memberzimvbcoder3-Jun-10 2:13 
Generalvery nice article Pin
Thanigainathan.S1-Jun-10 3:45
memberThanigainathan.S1-Jun-10 3:45 
GeneralRe: very nice article Pin
jpaulino2-Jun-10 10:27
memberjpaulino2-Jun-10 10:27 
GeneralNice to see you won again Pin
Marcelo Ricardo de Oliveira31-May-10 15:05
memberMarcelo Ricardo de Oliveira31-May-10 15:05 
GeneralRe: Nice to see you won again Pin
jpaulino31-May-10 20:29
memberjpaulino31-May-10 20:29 
GeneralWorkaround for C# Xml Literals Pin
Jaime Olivares31-May-10 10:15
memberJaime Olivares31-May-10 10:15 
GeneralRe: Workaround for C# Xml Literals Pin
jpaulino31-May-10 12:51
memberjpaulino31-May-10 12:51 
GeneralXML literals for SQL statements Pin
GlimmerMan21-Apr-10 3:38
memberGlimmerMan21-Apr-10 3:38 
GeneralRe: XML literals for SQL statements Pin
jpaulino22-Apr-10 21:26
memberjpaulino22-Apr-10 21:26 
GeneralRe: XML literals for SQL statements Pin
GlimmerMan23-Apr-10 4:23
memberGlimmerMan23-Apr-10 4:23 
GeneralRe: XML literals for SQL statements Pin
jpaulino23-Apr-10 4:35
memberjpaulino23-Apr-10 4:35 
GeneralThanks for the tips Pin
zimvbcoder15-Apr-10 3:52
memberzimvbcoder15-Apr-10 3:52 
GeneralRe: Thanks for the tips Pin
jpaulino15-Apr-10 9:11
memberjpaulino15-Apr-10 9:11 
GeneralDoesn't this only work for VB.NET Pin
Sacha Barber13-Apr-10 22:03
mvpSacha Barber13-Apr-10 22:03 
GeneralRe: Doesn't this only work for VB.NET [modified] Pin
jpaulino13-Apr-10 22:19
memberjpaulino13-Apr-10 22:19 
GeneralRe: Doesn't this only work for VB.NET Pin
Sacha Barber13-Apr-10 22:23
mvpSacha Barber13-Apr-10 22:23 
GeneralRe: Doesn't this only work for VB.NET Pin
RugbyLeague14-Apr-10 22:11
memberRugbyLeague14-Apr-10 22:11 
GeneralRe: Doesn't this only work for VB.NET Pin
jpaulino14-Apr-10 22:20
memberjpaulino14-Apr-10 22:20 
GeneralRe: Doesn't this only work for VB.NET Pin
RugbyLeague14-Apr-10 22:25
memberRugbyLeague14-Apr-10 22:25 
GeneralRe: Doesn't this only work for VB.NET Pin
RDoes31-May-10 9:35
memberRDoes31-May-10 9:35 
GeneralDataTable to XmlLiteral Error Pin
petersgyoung12-Apr-10 21:55
memberpetersgyoung12-Apr-10 21:55 
GeneralRe: DataTable to XmlLiteral Error Pin
jpaulino13-Apr-10 4:05
memberjpaulino13-Apr-10 4:05 
GeneralRe: DataTable to XmlLiteral Error Pin
petersgyoung13-Apr-10 15:28
memberpetersgyoung13-Apr-10 15:28 
GeneralRe: DataTable to XmlLiteral Error Pin
jpaulino13-Apr-10 22:08
memberjpaulino13-Apr-10 22:08 
GeneralRe: DataTable to XmlLiteral Error Pin
petersgyoung16-Apr-10 20:41
memberpetersgyoung16-Apr-10 20:41 
Generalthanx Pin
Christ Kennedy11-Apr-10 10:50
memberChrist Kennedy11-Apr-10 10:50 
GeneralRe: thanx Pin
jpaulino11-Apr-10 11:16
memberjpaulino11-Apr-10 11:16 

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 | Terms of Use | Mobile
Web03 | 2.8.150901.1 | Last Updated 12 Apr 2010
Article Copyright 2010 by jpaulino
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid