Como: Inserir expressões nos literais XML (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.

A sintaxe de uma expressão incorporada é <%= exp %>, que é a mesma sintaxe que ASP.NET usa. Para obter mais informações, consulte Expressões inseridas no 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>
    

Consulte também

Tarefas

Como: Criar literais XML (Visual Basic)

Conceitos

Expressões inseridas no XML (Visual Basic)

Outros recursos

Criando XML em Visual Basic

XML no Visual Basic