XML Literals and XML Axis Properties

XML literals are a VB-exclusive feature: you can write XML directly in code.

28.1 Creating XML

Dim customers = {
    New With {.Id = 1, .Name = "Ana", .City = "Pune"},
    New With {.Id = 2, .Name = "Bo", .City = "Mumbai"}
}

Dim doc = <?xml version="1.0" encoding="utf-8"?>
          <customers generated=<%= Date.Now.ToString("s") %>>
              <%= From c In customers
                  Select <customer id=<%= c.Id %>>
                             <name><%= c.Name %></name>
                             <city><%= c.City %></city>
                         </customer> %>
          </customers>

doc.Save("customers.xml")
Console.WriteLine(doc)

Dim element As XElement = <book title="VB Guide" year="2025"><author>Ana</author></book>

28.2 Querying XML with Axis Properties

Dim xml = XDocument.Load("customers.xml")

For Each c In xml.<customers>.<customer>          ' child axis: .<name>
    Console.WriteLine($"{c.@id}: {c.<name>.Value} from {c.<city>.Value}")   ' attribute axis: .@attr
Next

Dim allNames = From n In xml...<name> Select n.Value     ' descendant axis: ...<name>
Dim firstCity = xml...<city>.First().Value
Dim punes = From c In xml...<customer>
            Where c.<city>.Value = "Pune"
            Select c.<name>.Value

28.3 XML Namespaces

Imports <xmlns:inv="http://example.com/invoice">
Dim invoice = <inv:invoice><inv:total>100</inv:total></inv:invoice>
Console.WriteLine(invoice.<inv:total>.Value)

28.4 Embedded Expressions for Templating

Dim html = <html>
               <body>
                   <h1><%= title %></h1>
                   <ul><%= From i In items Select <li><%= i %></li> %></ul>
               </body>
           </html>
File.WriteAllText("report.html", html.ToString())