XML Literals
Prerequisites: LINQ
Visual Basic has a feature C# lacks: XML literals. You can write XML directly in code, embed expressions in it, and query it with special axis properties.
Building XML
Module Program
Sub Main()
Dim products = {("Tea", 3.5D), ("Coffee", 4.25D)}
Dim catalog =
<catalog updated="2025-03-09">
<%= From p In products
Select <product price=<%= p.Item2 %>><%= p.Item1 %></product> %>
</catalog>
Console.WriteLine(catalog)
End Sub
End Module
<catalog updated="2025-03-09">
<product price="3.5">Tea</product>
<product price="4.25">Coffee</product>
</catalog>
- The XML is checked by the compiler — a missing closing tag is a compile error.
<%= expression %>embeds a value, or even a whole LINQ query that produces elements.- The result is an
XElementfrom LINQ to XML (System.Xml.Linq), which VB projects import automatically.
Reading XML with axis properties
Module Program
Sub Main()
Dim doc =
<orders>
<order id="1" status="paid"><total>42.50</total></order>
<order id="2" status="pending"><total>18.00</total></order>
<order id="3" status="paid"><total>7.25</total></order>
</orders>
For Each o In doc.<order>
Console.WriteLine($"order {o.@id}: {o.@status}, {o.<total>.Value}")
Next
Dim paidTotal = Aggregate o In doc.<order>
Where o.@status = "paid"
Into Sum(Decimal.Parse(o.<total>.Value, Globalization.CultureInfo.InvariantCulture))
Console.WriteLine($"paid total: {paidTotal}")
Console.WriteLine(doc...<total>.Count())
End Sub
End Module
order 1: paid, 42.50
order 2: pending, 18.00
order 3: paid, 7.25
paid total: 49.75
3
| Syntax | Meaning |
|---|---|
x.<child> |
child elements named child |
x.@attr |
the value of an attribute |
x...<name> |
descendants at any depth |
.Value |
the text of the first matching element |
Loading and saving files
Module Program
Sub Main()
Dim settings = <settings><theme>dark</theme><fontSize>14</fontSize></settings>
settings.Save("settings.xml")
Dim loaded = XElement.Load("settings.xml")
loaded.<theme>.Value = "light"
Console.WriteLine(loaded.<theme>.Value & " " & CInt(loaded.<fontSize>.Value))
End Sub
End Module
light 14
XML literals make VB a pleasant language for configuration files, reports, and data exchange with older systems. You can check XML output with the XML Formatter or XML Validator.