
Embedded Expression Location and Validation
Embedded expressions can appear only at certain locations within XML literal expressions. The expression location controls which types the expression can return and how Nothing is handled. The following table describes the allowed locations and types of embedded expressions.
Location in literal
|
Type of expression
|
Handling of Nothing
|
|---|
XML element name
|
XName
|
Error
|
XML element content
|
Object or array of Object
|
Ignored
|
XML element attribute name
|
XName
|
Error, unless the attribute value is also Nothing
|
XML element attribute value
|
Object
|
Attribute declaration ignored
|
XML element attribute
|
XAttribute or a collection of XAttribute
|
Ignored
|
XML document root element
|
XElement or a collection of one XElement object and an arbitrary number of XProcessingInstruction and XComment objects
|
Ignored
|
Example of an embedded expression in an XML element name:
Dim elementName As String = "contact"
Dim contact1 As XElement = <<%= elementName %>/>
Example of an embedded expression in the content of an XML element:
Dim contactName As String = "Patrick Hines"
Dim contact2 As XElement = _
<contact><%= contactName %></contact>
Example of an embedded expression in an XML element attribute name:
Dim phoneType As String = "home"
Dim contact3 As XElement = _
<contact <%= phoneType %>="206-555-0144"/>
Example of an embedded expression in an XML element attribute value:
Dim phoneNumber As String = "206-555-0144"
Dim contact4 As XElement = _
<contact home=<%= phoneNumber %>/>
Example of an embedded expression in an XML element attribute:
Dim phoneAttribute As XAttribute = _
New XAttribute(XName.Get(phoneType), phoneNumber)
Dim contact5 As XElement = _
<contact <%= phoneAttribute %>/>
Example of an embedded expression in an XML document root element:
Dim document As XDocument = _
<?xml version="1.0"?><%= contact1 %>
If you enable Option Strict, the compiler checks that the type of each embedded expression widens to the required type. The only exception is for the root element of an XML document, which is verified when the code runs. If you compile without Option Strict, you can embed expressions of type Object and their type is verified at run time.
In locations where content is optional, embedded expressions that contain Nothing are ignored. This means you do not have to check that element content, attribute values, and array elements are not Nothing before you use an XML literal. Required values, such as element and attribute names, cannot be Nothing.
For more information about using an embedded expression in a particular type of literal, see XML Document Literal, XML Element Literal.