Xml Literals

AID: 2897
  • Status: Published

9740 points

  • Byjpaulino
  • TypeTutorial
  • Posted on2010-04-19 at 05:59:29
Awards
  • Community Pick
  • Experts Exchange Approved

XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String Literal, only instead of starting and ending with with a quote character ("), it begins with (<) and ends with (>).  You can use regular XML tags right there in the code!

xmlliterals0.jpg
  • 75 KB
  • code
code



Introduction


XML Literals allow you to use XML syntax in your code.  It’s easy to work with XML files and XML fragments this way, since you have the tags 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) it 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 recognized by the intellisense system, making it very convenient to use.  It even does the indenting automatically.

Topics in this article:


  • XML Literals
  • Read Information
  • List Information
  • Embedded Expressions
  • Modify Nodes
  • Inserting Nodes
  • Deleting Nodes
  • Finally Example (web)


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>.Value 
        MessageBox.Show(msg, "XML Literals")
                                  
1:
2:
3:
4:
5:

Select allOpen in new window



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

xmlliterals1.jpg
  • 23 KB
  • msgbox
msgbox



You can create your XML file in runtime mode.  Here’s an example 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> 
        <magazine> 
            <magazineName>"MSDN Magazine"</magazineName> 
            <magazineName>"Code Magazine"</magazineName> 
        </magazine> 
    </library>
                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window



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")
                                  
1:

Select allOpen in new window



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() method. This will load the file and show the magazine name, using the Descendants property.

Descendants property allow you to access to the descendant nodes by name, using a triple-dot (...), from a XElement or XDocument object:

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

Select allOpen in new window


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)
                                  
1:
2:
3:

Select allOpen in new window


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)
                                  
1:
2:

Select allOpen in new window


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)
                                  
1:
2:
3:

Select allOpen in new window



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)
                                  
1:
2:

Select allOpen in new window



Next You can also use the Descendants property (...) and simplify the code significantly:

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

Select allOpen in new window



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
                                  
1:
2:
3:
4:
5:
6:

Select allOpen in new window



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
                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window



Embedded Expressions

Embedded expressions are expressions that you can use in the XML code, using the tags
    <%= expression %>
much the same wasy as it's done 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 straightforward 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>
                                  
1:
2:
3:
4:
5:
6:

Select allOpen in new window



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 a 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")
                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window


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")
                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:

Select allOpen in new window


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 a 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")
                                  
1:
2:
3:

Select allOpen in new window


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")
                                  
1:
2:
3:
4:
5:

Select allOpen in new window


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")
                                  
1:
2:
3:
4:

Select allOpen in new window



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")
                                  
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window


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")
                                  
1:
2:
3:
4:
5:

Select allOpen in new window


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")
                                  
1:
2:
3:

Select allOpen in new window



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")
                                  
1:
2:
3:

Select allOpen in new window



Finally Example (web)

You can use XML Literals also 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 shows how powerful and easy is to work with XML Literals.

Dim xmlFile = XDocument.Load("http://feeds.feedburner.com/vbtuga") 
Dim blogList = xmlFile...<item>.Where(Function(f) _ 
                f.<category>.Value = "VB.NET").<title>.ToList() 
For Each item As XElement In blogList 
    Console.WriteLine(item.Value) 
Next 
Console.ReadKey()
                                  
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window



And here's the resulting console output:

xmlliterals2.jpg
  • 54 KB
  • console
console



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, quickly and without complications.

This is an English version of some articles I posted a while ago in my blog and I hope this article helps you to become better with XML Literals, and use them more!

    Asked On
    2010-04-19 at 05:59:29ID2897
    Tags

    VB.NET

    ,

    Xml Literals

    ,

    .NET Framework 3.5

    Topic

    Microsoft Visual Basic.Net

    Views
    2910

    Comments

    Expert Comment

    by: DanRollins on 2010-04-19 at 16:46:32ID: 13487

    Great Article!   Got a big Yes vote from me!

    Expert Comment

    by: kevp75 on 2010-11-08 at 13:34:36ID: 21187

    Great article, thanks for the info!

    Expert Comment

    by: jstlawyers on 2011-02-04 at 01:13:27ID: 23494

    excellent article

    Add your Comment

    Please Sign up or Log in to comment on this article.

    Loading Advertisement...

    Top Visual Basic.NET Experts

    1. CodeCruiser

      461,941

      Wizard

      0 points yesterday

      Profile
      Rank: Genius
    2. kaufmed

      73,124

      Master

      3,000 points yesterday

      Profile
      Rank: Genius
    3. Masteraco

      68,140

      Master

      0 points yesterday

      Profile
      Rank: Guru
    4. Idle_Mind

      41,742

      10 points yesterday

      Profile
      Rank: Savant
    5. JamesBurger

      41,252

      0 points yesterday

      Profile
      Rank: Sage
    6. emoreau

      32,448

      500 points yesterday

      Profile
      Rank: Genius
    7. TheLearnedOne

      28,812

      0 points yesterday

      Profile
      Rank: Savant
    8. RolandDeschain

      24,308

      0 points yesterday

      Profile
      Rank: Sage
    9. nepaluz

      24,150

      20 points yesterday

      Profile
      Rank: Wizard
    10. MlandaT

      19,412

      0 points yesterday

      Profile
      Rank: Sage
    11. Stephan_Schrandt

      17,036

      0 points yesterday

      Profile
      Rank: Guru
    12. navneethegde

      14,932

      0 points yesterday

      Profile
      Rank: Wizard
    13. ddayx10

      14,000

      0 points yesterday

      Profile
      Rank: Sage
    14. gman84

      10,270

      0 points yesterday

      Profile
    15. tommyBoy

      9,850

      0 points yesterday

      Profile
      Rank: Sage
    16. nishantcomp2512

      9,450

      0 points yesterday

      Profile
      Rank: Guru
    17. vbigham

      9,100

      0 points yesterday

      Profile
      Rank: Master
    18. Cluskitt

      8,600

      0 points yesterday

      Profile
      Rank: Wizard
    19. AhmedHindy

      8,200

      0 points yesterday

      Profile
    20. matthewspatrick

      7,100

      0 points yesterday

      Profile
      Rank: Savant
    21. angelIII

      6,800

      0 points yesterday

      Profile
      Rank: Elite
    22. Dhaest

      6,684

      0 points yesterday

      Profile
      Rank: Genius
    23. AndyAinscow

      5,488

      0 points yesterday

      Profile
      Rank: Genius
    24. rick_gwu

      5,200

      0 points yesterday

      Profile
      Rank: Wizard
    25. Cenjoy100

      5,068

      0 points yesterday

      Profile

    Hall Of Fame