Compartir a través de


How to: Embed Expressions in XML Literals (Visual Basic)

You can combine XML literals with embedded expressions to create an XML document, fragment, or element that contains content created at run time. The following examples demonstrate how to use embedded expressions to populate element content, attributes, and element names at run time.

The syntax for an embedded expression is <%= exp %>, which is the same syntax that ASP.NET uses. For more information, see Embedded Expressions in XML (Visual Basic).

You can also use the LINQ to XML APIs to create LINQ to XML objects. For more information, see XElement.

Procedures

To insert text as element content

  • The following example shows how to insert the text that is contained in the contactName variable between the opening and closing name elements.

    Dim contactName As String = "Patrick Hines" 
    Dim contact As XElement = 
      <contact>
        <name><%= contactName %></name>
      </contact>
    Console.WriteLine(contact)
    

    This example produces the following output:

    <contact>
      <name>Patrick Hines</name>
    </contact>
    

To insert text as an attribute value

  • The following example shows how to insert the text that is contained in the phoneType variable as the value of the type attribute.

    Dim phoneType As String = "home" 
    Dim contact2 As XElement = 
      <contact>
        <phone type=<%= phoneType %>>206-555-0144</phone>
      </contact>
    Console.WriteLine(contact2)
    

    This example produces the following output:

    <contact>
      <phone type="home">206-555-0144</phone>
    </contact>
    

To insert text for an element name

  • The following example shows how to insert the text that is contained in the elementName variable as the name of an element.

    When creating elements by using this technique, you must close them with the </> tag.

    Dim elementName As String = "contact" 
    Dim contact3 As XElement = 
        <<%= elementName %>>
            <name>Patrick Hines</name>
        </>
    Console.WriteLine(contact3)
    

    This example produces the following output:

    <contact>
      <name>Patrick Hines</name>
    </contact>
    

See Also

Tasks

How to: Create XML Literals (Visual Basic)

Concepts

Embedded Expressions in XML (Visual Basic)

Other Resources

Creating XML in Visual Basic

XML in Visual Basic