Export (0) Print
Expand All
1 out of 1 rated this helpful - Rate this topic

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.

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>
    
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.