Sideway
output.to from Sideway
Draft for Information Only

Content

VB.NET XML
 See also
  Overview of LINQ to XML in Visual Basic
 Creating XML
 Accessing and Navigating XML
 XML Namespaces
  Using XML Namespaces in XML Literals
  Using XML Namespaces in XML Axis Properties
 See also
  Creating XML in Visual Basic
 See also
  XML Literals Overview
 Simple Literals
 Line Continuation
 Embedding Queries in XML Literals
 How the Compiler Creates Objects from XML Literals
 See also
  Embedded Expressions in XML
 Embedded Expression Location and Validation
 Scoping Rules
 See also
  Names of Declared XML Elements and Attributes
 Rules
  Name Length Guidelines
 Case Sensitivity in Names
 XML Namespaces
 See also
  XML Literals and the XML 1.0 Specification
 What Visual Basic Does Not Support
 Extra Features That Visual Basic Supports
 See also
  White Space in XML Literals
 Significant and Insignificant White Space
 Examples
 See also
  How to: Create XML Literals
  To create an XML element
  To create an XML document
 See also
  How to: Embed Expressions in XML Literals
 Procedures
   To insert text as element content
   To insert text as an attribute value
   To insert text for an element name
 See also
  Manipulating XML in Visual Basic
 Related Sections
 See also
  How to: Load XML from a File, String, or Stream
  To load XML from a file
  To load XML from a string
  To load XML from a stream
 See also
  How to: Transform XML by Using LINQ
  To transform an XML document
 See also
  How to: Modify XML Literals
  To modify the value of an XML literal
  To add an attribute to an XML literal
  To add an element to an XML literal
  To remove an element or attribute from an XML literal
  To modify an XML literal
 See also
  Accessing XML in Visual Basic
  XML Axis Properties
 Related Sections
  How to: Access XML Descendant Elements
 Example
 Compiling the Code
 See also
  How to: Access XML Child Elements
 Example
 Compiling the Code
 See also
  How to: Access XML Attributes
 Example
 See also
  How to: Declare and Use XML Namespace Prefixes
 Example
 Compiling the Code
 See also
  Source/Reference

VB.NET XML

Visual Basic provides integrated language support that enables it to interact with LINQ to XML.

See also

Overview of LINQ to XML in Visual Basic

Visual Basic provides support for LINQ to XML through XML literals and XML axis properties. This enables you to use a familiar, convenient syntax for working with XML in your Visual Basic code. XML literals enable you to include XML directly in your code. XML axis properties enable you to access child nodes, descendant nodes, and attributes of an XML literal. For more information, see XML Literals Overview and Accessing XML in Visual Basic.

LINQ to XML is an in-memory XML programming API designed specifically to take advantage of Language-Integrated Query (LINQ). Although you can call the LINQ APIs directly, only Visual Basic enables you to declare XML literals and directly access XML axis properties.

Note

XML literals and XML axis properties are not supported in declarative code in an ASP.NET page. To use Visual Basic XML features, put your code in a code-behind page in your ASP.NET application.

Play button For related video demonstrations, see How Do I Get Started with LINQ to XML? and How Do I Create Excel Spreadsheets using LINQ to XML?.

Creating XML

There are two ways to create XML trees in Visual Basic. You can declare an XML literal directly in code, or you can use the LINQ APIs to create the tree. Both processes enable the code to reflect the final structure of the XML tree. For example, the following code example creates an XML element:

VB
Dim contact1 As XElement = 
    <contact>
      <name>Patrick Hines</name>
      <phone type="home">206-555-0144</phone>
      <phone type="work">425-555-0145</phone>
    </contact>

For more information, see Creating XML in Visual Basic.

Accessing and Navigating XML

Visual Basic provides XML axis properties for accessing and navigating XML structures. These properties enable you to access XML elements and attributes by specifying the XML child element names. Alternatively, you can explicitly call the LINQ methods for navigating and locating elements and attributes. For example, the following code example uses XML axis properties to refer to the attributes and child elements of an XML element. The code example uses a LINQ query to retrieve child elements and output them as XML elements, effectively performing a transform.

VB
' Place Imports statements at the top of your program.  
Imports <xmlns:ns="http://SomeNamespace">

Module Sample1

    Sub SampleTransform()

        ' Create test by using a global XML namespace prefix. 

        Dim contact = 
            <ns:contact>
                <ns:name>Patrick Hines</ns:name>
                <ns:phone ns:type="home">206-555-0144</ns:phone>
                <ns:phone ns:type="work">425-555-0145</ns:phone>
            </ns:contact>

        Dim phoneTypes = 
          <phoneTypes>
              <%= From phone In contact.<ns:phone> 
                  Select <type><%= phone.@ns:type %></type> 
              %>
          </phoneTypes>

        Console.WriteLine(phoneTypes)
    End Sub

End Module

For more information, see Accessing XML in Visual Basic.

XML Namespaces

Visual Basic enables you to specify an alias to a global XML namespace by using the Imports statement. The following example shows how to use the Imports statement to import an XML namespace:

VB
Imports <xmlns:ns="http://someNamespace">

You can use an XML namespace alias when you access XML axis properties and declare XML literals for XML documents and elements.

You can retrieve an XNamespace object for a particular namespace prefix by using the GetXmlNamespace Operator.

For more information, see Imports Statement (XML Namespace).

Using XML Namespaces in XML Literals

The following example shows how to create an XElement object that uses the global namespace ns:

VB
Dim contact1 As XElement = 
    <ns:contact>
        <ns:name>Patrick Hines</ns:name>
        <ns:phone type="home">206-555-0144</ns:phone>
        <ns:phone type="work">425-555-0145</ns:phone>
    </ns:contact>

Console.WriteLine(contact1)

The Visual Basic compiler translates XML literals that contain XML namespace aliases into equivalent code that uses the XML notation for using XML namespaces, with the xmlns attribute. When compiled, the code in the previous section's example produces essentially the same executable code as the following example:

VB
Dim contact2 As XElement = 
    <ns1:contact xmlns:ns1="http://someNamespace">
        <ns1:name>Patrick Hines</ns1:name>
        <ns1:phone type="home">206-555-0144</ns1:phone>
        <ns1:phone type="work">425-555-0145</ns1:phone>
    </ns1:contact>

Console.WriteLine(contact2)

Using XML Namespaces in XML Axis Properties

XML namespaces declared in XML literals are not available for use in XML axis properties. However, global namespaces can be used with the XML axis properties. Use a colon to separate the XML namespace prefix from the local element name. Following is an example:

VB
Console.WriteLine("Contact name is: " & contact1.<ns:name>.Value)

See also

Creating XML in Visual Basic

Visual Basic enables you to use XML literals directly in your code. The XML literal syntax represents LINQ to XML objects, and it is similar to the XML 1.0 syntax. This makes it easier to create XML elements, documents, and fragments programmatically because your code has the same structure as the final XML.

See also

XML Literals Overview

An XML literal allows you to incorporate XML directly into your Visual Basic code. The XML literal syntax represents LINQ to XML objects, and it is the similar to the XML 1.0 syntax. This makes it easier to create XML elements and documents programmatically because your code has the same structure as the final XML.

Visual Basic compiles XML literals into LINQ to XML objects. LINQ to XML provides a simple object model for creating and manipulating XML, and this model integrates well with Language-Integrated Query (LINQ). For more information, see XElement.

You can embed a Visual Basic expression in an XML literal. At run time, your application creates a LINQ to XML object for each literal, incorporating the values of the embedded expressions. This lets you specify dynamic content inside an XML literal. For more information, see Embedded Expressions in XML.

For more information about the differences between the XML literal syntax and the XML 1.0 syntax, see XML Literals and the XML 1.0 Specification.

Simple Literals

You can create a LINQ to XML object in your Visual Basic code by typing or pasting in valid XML. An XML element literal returns an XElement object. For more information, see XML Element Literal and XML Literals and the XML 1.0 Specification. The following example creates an XML element that has several child elements.

VB
Dim contact1 As XElement = 
    <contact>
      <name>Patrick Hines</name>
      <phone type="home">206-555-0144</phone>
      <phone type="work">425-555-0145</phone>
    </contact>

You can create an XML document by starting an XML literal with <?xml version="1.0"?>, as shown in the following example. An XML document literal returns an XDocument object. For more information, see XML Document Literal.

VB
Dim contactDoc As XDocument = 
    <?xml version="1.0"?>
    <contact>
      <name>Patrick Hines</name>
      <phone type="home">206-555-0144</phone>
      <phone type="work">425-555-0145</phone>
    </contact>

Note

The XML literal syntax in Visual Basic is not identical to the syntax in the XML 1.0 specification. For more information, see XML Literals and the XML 1.0 Specification.

Line Continuation

An XML literal can span multiple lines without using line continuation characters (the space-underscore-enter sequence). This makes it easier to compare XML literals in code with XML documents.

The compiler treats line continuation characters as part of an XML literal. Therefore, you should use the space-underscore-enter sequence only when it belongs in the LINQ to XML object.

However, you do need line continuation characters if you have a multiline expression in an embedded expression. For more information, see Embedded Expressions in XML.

Embedding Queries in XML Literals

You can use a query in an embedded expression. When you do this, the elements returned by the query are added to the XML element. This lets you add dynamic content, such as the result of a user's query, to an XML literal.

For example, the following code uses an embedded query to create XML elements from the members of the phoneNumbers2 array and then add those elements as children of contact2.

VB
Public Class XmlSamples

  Public Sub Main()
    ' Initialize the objects. 

    Dim phoneNumbers2 As Phone() = { 
        New Phone("home", "206-555-0144"), 
        New Phone("work", "425-555-0145")}

    ' Convert the data contained in phoneNumbers2 to XML. 

    Dim contact2 = 
        <contact>
          <name>Patrick Hines</name>
          <%= From p In phoneNumbers2 
            Select <phone type=<%= p.Type %>><%= p.Number %></phone> 
          %>
        </contact>

    Console.WriteLine(contact2)
  End Sub

End Class

Class Phone
  Public Type As String
  Public Number As String
  Public Sub New(ByVal t As String, ByVal n As String)
    Type = t
    Number = n
  End Sub
End Class

How the Compiler Creates Objects from XML Literals

The Visual Basic compiler translates XML literals into calls to the equivalent LINQ to XML constructors to build up the LINQ to XML object. For example, the Visual Basic compiler will translate the following code example into a call to the XProcessingInstruction constructor for the XML version instruction, calls to the XElement constructor for the <contact>, <name>, and <phone> elements, and calls to the XAttribute constructor for the type attribute. Specifically, given the attributes in the following sample, the Visual Basic compiler will call the XAttribute(XName, Object) constructor twice. The first will pass the value type for the name parameter and the value home for the value parameter. The second will also pass the value type for the name parameter, but the value work for the value parameter.

VB
Dim contactDoc As XDocument = 
    <?xml version="1.0"?>
    <contact>
      <name>Patrick Hines</name>
      <phone type="home">206-555-0144</phone>
      <phone type="work">425-555-0145</phone>
    </contact>

See also

Embedded Expressions in XML

Embedded expressions enable you to create XML literals that contain expressions that are evaluated at run time. The syntax for an embedded expression is <%= expression %>, which is the same as the syntax used in ASP.NET.

For example, you can create an XML element literal, combining embedded expressions with literal text content.

VB
Dim isbnNumber As String = "12345"
Dim modifiedDate As String = "3/5/2006"
Dim book As XElement = 
    <book category="fiction" isbn=<%= isbnNumber %>>
        <modifiedDate><%= modifiedDate %></modifiedDate>
    </book>

If isbnNumber contains the integer 12345 and modifiedDate contains the date 3/5/2006, when this code executes, the value of book is:

XML
<book category="fiction" isbn="12345">  
  <modifiedDate>3/5/2006</modifiedDate>  
</book>  

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:

    VB
    Dim elementName As String = "contact"
    Dim contact1 As XElement = <<%= elementName %>/>
    
  • Example of an embedded expression in the content of an XML element:

    VB
    Dim contactName As String = "Patrick Hines"
    Dim contact2 As XElement = 
      <contact><%= contactName %></contact>
    
  • Example of an embedded expression in an XML element attribute name:

    VB
    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:

    VB
    Dim phoneNumber As String = "206-555-0144"
    Dim contact4 As XElement = 
      <contact home=<%= phoneNumber %>/>
    
  • Example of an embedded expression in an XML element attribute:

    VB
    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:

    VB
    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.

Scoping Rules

The compiler converts each XML literal into a constructor call for the appropriate literal type. The literal content and embedded expressions in an XML literal are passed as arguments to the constructor. This means that all Visual Basic programming elements available to an XML literal are also available to its embedded expressions.

Within an XML literal, you can access the XML namespace prefixes declared with the Imports statement. You can declare a new XML namespace prefix, or shadow an existing XML namespace prefix, in an element by using the xmlns attribute. The new namespace is available to the child nodes of that element, but not to XML literals in embedded expressions.

Note

When you declare an XML namespace prefix by using the xmlns namespace attribute, the attribute value must be a constant string. In this regard, using the xmlns attribute is like using the Imports statement to declare an XML namespace. You cannot use an embedded expression to specify the XML namespace value.

See also

Names of Declared XML Elements and Attributes

This topic provides Visual Basic guidelines for naming XML elements and attributes in XML literals. In an XML literal, you can specify a local name or a qualified name. A qualified name consists of an XML namespace prefix, a colon, and a local name. For more information about XML namespace prefixes, see XML Element Literal.

Rules

A local name of an element or attribute in Visual Basic must adhere to the following rules.

  • It can begin with a namespace. It must begin with an alphabetical character or an underscore (_).

  • It must contain only alphabetical characters, decimal digits, underscores, periods (.), and hyphens (-).

  • It must not be more than 1,024 characters long.

  • Colons that appear in names indicate namespace demarcation. Therefore, you can use colons only to specify an XML namespace for a particular name.

In addition, you should adhere to the following guideline.

  • The XML 1.0 specification reserves all names starting with the string "xml", of any capitalization variation. Therefore, do not use those names for your element and attribute names.

Name Length Guidelines

As a practical matter, a name should be as short as possible while still clearly identifying the nature of the element. This improves the readability of your code and reduces line length and source-file size.

However, your name should not be so short that it does not adequately describe the element or how your code uses it. This is important for the readability of your code. If somebody else is trying to understand it, or if you yourself are looking at it a long time after you wrote it, appropriate element names can save time.

Case Sensitivity in Names

XML element names are case sensitive. This means that when the Visual Basic compiler compares two names that differ in alphabetical case only, it interprets them as different names. For example, it interprets ABC and abc as referring to separate elements.

XML Namespaces

When creating an XML element literal, you can specify the XML namespace prefix for the element name. For more information, see XML Element Literal.

See also

XML Literals and the XML 1.0 Specification

The XML literal syntax in Visual Basic supports most of the Extensible Markup Language (XML) 1.0 specification. For details about the XML 1.0 specification, see Extensible Markup Language (XML) 1.0 on the W3C Web site.

What Visual Basic Does Not Support

  • An XML literal cannot contain a document type definition (DTD).

  • An XML document literal must start with an XML document declaration.

  • An XML literal cannot contain more than 65,535 characters on one line.

  • XML namespace prefixes, element names, and attribute names cannot contain more than 1,024 characters.

Extra Features That Visual Basic Supports

  • The embedded expression syntax allowed in document and element literals is not valid XML.

See also

White Space in XML Literals

The Visual Basic compiler incorporates only the significant white space characters from an XML literal when it creates a LINQ to XML object. The insignificant white space characters are not incorporated.

Significant and Insignificant White Space

White space characters in XML literals are significant in only three areas:

  • When they are in an attribute value.

  • When they are part of an element's text content and the text also contains other characters.

  • When they are in an embedded expression for an element's text content.

Otherwise, the compiler treats white space characters as insignificant and does not include then in the LINQ to XML object for the literal.

To include insignificant white space in an XML literal, use an embedded expression that contains a string literal with the white space.

Note

If the xml:space attribute appears in an XML element literal, the Visual Basic compiler includes the attribute in the XElement object, but adding this attribute does not change how the compiler treats white space.

Examples

The following example contains two XML elements, outer and inner. Both elements contain white space in their text content. The white space in the outer element is insignificant because it contains only white space and an XML element. The white space in the inner element is significant because it contains white space and text.

VB
Dim example As XElement = <outer>
                              <inner> 
                                  Inner text 
                              </inner>
                          </outer>

Console.WriteLine(example)

When run, this code displays the following text.

XML
<outer>  
  <inner>  
                                          Inner text  
                                      </inner>  
</outer>  

See also

How to: Create XML Literals

You can create an XML document, fragment, or element directly in code by using an XML literal. The examples in this topic demonstrate how to create an XML element that has three child elements, and how to create an XML document.

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

To create an XML element

  • Create the XML inline by using the XML literal syntax, which is the same as the actual XML syntax.

    VB
    Dim contact1 As XElement = 
        <contact>
          <name>Patrick Hines</name>
          <phone type="home">206-555-0144</phone>
          <phone type="work">425-555-0145</phone>
        </contact>
    

    Run the code. The output of this code is:

    <contact>

    <name>Patrick Hines</name>

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

    <phone type="work">425-555-0145</phone>

    </contact>

To create an XML document

  • Create the XML document inline. The following code creates an XML document that has literal syntax, an XML declaration, a processing instruction, a comment, and an element that contains another element.

    VB
    Dim libraryRequest As XDocument = 
        <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        <?xml-stylesheet type="text/xsl" href="show_book.xsl"?>
        <!-- Tests that the application works. -->
        <books>
            <book/>
        </books>
    Console.WriteLine(libraryRequest)
    

    Run the code. The output of this code is:

    <?xml-stylesheet type="text/xsl" href="show_book.xsl"?>

    <!-- Tests that the application works. -->

    <books>

    <book/>

    </books>

See also

How to: Embed Expressions in XML Literals

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.

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.

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

    This example produces the following output:

    XML
    <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.

    VB
    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:

    XML
    <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.

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

    This example produces the following output:

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

See also

Manipulating XML in Visual Basic

You can use XML literals to load XML from an external source such as a string, file, or stream. You can then use LINQ to XML to manipulate the XML and use Language-Integrated Query (LINQ) to query the XML.

Related Sections

XML Axis Properties
Provides links to sections that describe the various XML access properties.

Overview of LINQ to XML in Visual Basic
Provides an introduction to using LINQ to XML in Visual Basic.

Creating XML in Visual Basic
Provides an introduction to using XML literals in Visual Basic.

Accessing XML in Visual Basic
Demonstrates how to access parts of an XML element or document in Visual Basic.

XML
Provides links to sections that describe how to use LINQ to XML in Visual Basic.

See also

How to: Load XML from a File, String, or Stream

You can create XML Literals and populate them with the contents from an external source such as a file, a string, or a stream by using several methods. These methods are shown in the following examples.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Personalizing the IDE.

To load XML from a file

  • To populate an XML literal such as an XElement or XDocument object from a file, use the Load method. This method can take a file path, text stream, or XML stream as input.

    The following code example shows the use of the Load(String) method to populate an XDocument object with XML from a text file.

    VB
    Dim books = 
        XDocument.Load(My.Application.Info.DirectoryPath & 
                       "\..\..\Data\books.xml")
    Console.WriteLine(books)
    

To load XML from a string

  • To populate an XML literal such as an XElement or XDocument object from a string, you can use the Parse method.

    The following code example shows the use of the XDocument.Parse(String) method to populate an XDocument object with XML from a string.

    VB
    Dim xmlString = "<Book id=""bk102"">" & vbCrLf & 
                    "  <Author>Garcia, Debra</Author>" & vbCrLf & 
                    "  <Title>Writing Code</Title>" & vbCrLf & 
                    "  <Price>5.95</Price>" & vbCrLf & 
                    "</Book>"
    Dim xmlElem = XElement.Parse(xmlString)
    Console.WriteLine(xmlElem)
    

To load XML from a stream

The following code example shows the use of the ReadFrom method to populate an XDocument object with XML from an XML stream.

VB
Dim reader = 
  System.Xml.XmlReader.Create(My.Application.Info.DirectoryPath & 
                              "\..\..\Data\books.xml")
reader.MoveToContent()
Dim inputXml = XDocument.ReadFrom(reader)
Console.WriteLine(inputXml)

See also

How to: Transform XML by Using LINQ

XML Literals make it easy to read XML from one source and transform it to a new XML format. You can take advantage of LINQ queries to retrieve the content to transform, or change content in an existing document to a new XML format.

The example in this topic transforms content from an XML source document to HTML to be viewed in a browser.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Personalizing the IDE.

To transform an XML document

  1. In Visual Studio, create a new Visual Basic project in the Console Application project template.

  2. Double-click the Module1.vb file created in the project to modify the Visual Basic code. Add the following code to the Sub Main of the Module1 module. This code creates the source XML document as an XDocument object.

    VB
    Dim catalog =   
      <?xml version="1.0"?>  
        <Catalog>  
          <Book id="bk101">  
            <Author>Garghentini, Davide</Author>  
            <Title>XML Developer's Guide</Title>  
            <Price>44.95</Price>  
            <Description>  
              An in-depth look at creating applications  
              with <technology>XML</technology>. For   
              <audience>beginners</audience> or   
              <audience>advanced</audience> developers.  
            </Description>  
          </Book>  
          <Book id="bk331">  
            <Author>Spencer, Phil</Author>  
            <Title>Developing Applications with Visual Basic .NET</Title>  
            <Price>45.95</Price>  
            <Description>  
              Get the expert insights, practical code samples,   
              and best practices you need   
              to advance your expertise with <technology>Visual   
              Basic .NET</technology>.   
              Learn how to create faster, more reliable applications  
              based on professional,   
              pragmatic guidance by today's top <audience>developers</audience>.  
            </Description>  
          </Book>  
        </Catalog>  

    How to: Load XML from a File, String, or Stream.

  3. After the code to create the source XML document, add the following code to retrieve all the <Book> elements from the object and transform them into an HTML document. The list of <Book> elements is created by using a LINQ query that returns a collection of XElement objects that contain the transformed HTML. You can use embedded expressions to put the values from the source document in the new XML format.

    The resulting HTML document is written to a file by using the Save method.

    VB
    Dim htmlOutput =   
      <html>  
        <body>  
          <%= From book In catalog.<Catalog>.<Book>   
              Select <div>  
                       <h1><%= book.<Title>.Value %></h1>  
                       <h3><%= "By " & book.<Author>.Value %></h3>  
                        <h3><%= "Price = " & book.<Price>.Value %></h3>  
                        <h2>Description</h2>  
                        <%= TransformDescription(book.<Description>(0)) %>  
                        <hr/>  
                      </div> %>  
        </body>  
      </html>  
    
    htmlOutput.Save("BookDescription.html")  
  4. After Sub Main of Module1, add a new method (Sub) to transform a <Description> node into the specified HTML format. This method is called by the code in the previous step and is used to preserve the format of the <Description> elements.

    This method replaces sub-elements of the <Description> element with HTML. The ReplaceWith method is used to preserve the location of the sub-elements. The transformed content of the <Description> element is included in an HTML paragraph (<p>) element. The Nodes property is used to retrieve the transformed content of the <Description> element. This ensures that sub-elements are included in the transformed content.

    Add the following code after Sub Main of Module1.

    VB
    Public Function TransformDescription(ByVal desc As XElement) As XElement  
    
      ' Replace <technology> elements with <b>.  
      Dim content = (From element In desc...<technology>).ToList()  
    
      If content.Count > 0 Then  
        For i = 0 To content.Count - 1  
          content(i).ReplaceWith(<b><%= content(i).Value %></b>)  
        Next  
      End If  
    
      ' Replace <audience> elements with <i>.  
      content = (From element In desc...<audience>).ToList()  
    
      If content.Count > 0 Then  
        For i = 0 To content.Count - 1  
          content(i).ReplaceWith(<i><%= content(i).Value %></i>)  
        Next  
      End If  
    
      ' Return the updated contents of the <Description> element.  
      Return <p><%= desc.Nodes %></p>  
    End Function  
    
  5. Save your changes.

  6. Press F5 to run the code. The resulting saved document will resemble the following:

    <?xml version="1.0"?>  
    <html>  
      <body>  
        <div>  
          <h1>XML Developer's Guide</h1>  
          <h3>By Garghentini, Davide</h3>  
          <h3>Price = 44.95</h3>  
          <h2>Description</h2>  
          <p>  
            An in-depth look at creating applications  
            with <b>XML</b>. For   
            <i>beginners</i> or   
            <i>advanced</i> developers.  
          </p>  
          <hr />  
        </div>  
        <div>  
          <h1>Developing Applications with Visual Basic .NET</h1>  
          <h3>By Spencer, Phil</h3>  
          <h3>Price = 45.95</h3>  
          <h2>Description</h2>  
          <p>  
            Get the expert insights, practical code   
            samples, and best practices you need   
            to advance your expertise with <b>Visual   
            Basic .NET</b>. Learn how to create faster,  
            more reliable applications based on  
            professional, pragmatic guidance by today's   
            top <i>developers</i>.  
          </p>  
          <hr />  
        </div>  
      </body>  
    </html>  
    

See also

How to: Modify XML Literals

Visual Basic provides convenient ways to modify XML literals. You can add or delete elements and attributes, and you can also replace an existing element with a new XML element. This topic provides several examples of how to modify an existing XML literal.

To modify the value of an XML literal

  1. To modify the value of an XML literal, obtain a reference to the XML literal and set the Value property to the desired value.

    The following code example updates the value of all the <Price> elements in an XML document.

    VB
    For Each book In From element In catalog.<Catalog>.<Book>
      book.<Price>.Value = (book.<Price>.Value * 1.05).ToString("#.00")
    Next
    

    The following shows sample source XML and modified XML from this code example.

    Source XML:

    XML
    <?xml version="1.0"?>
    <Catalog>
      <Book id="bk101">
        <Author>Garghentini, Davide</Author>
        <Title>XML Developer's Guide</Title>
        <Price>44.95</Price>
      </Book>
      <Book id="bk331">
        <Author>Spencer, Phil</Author>
        <Title>Developing Applications with Visual Basic .NET</Title>
        <Price>45.95</Price>
      </Book>
    </Catalog>
    

    Modified XML:

    XML
    <?xml version="1.0"?>
    <Catalog>
      <Book id="bk101">
        <Author>Garghentini, Davide</Author>
        <Title>XML Developer's Guide</Title>
        <Price>47.20</Price>
      </Book>
      <Book id="bk331">
        <Author>Spencer, Phil</Author>
        <Title>Developing Applications with Visual Basic .NET</Title>
        <Price>48.25</Price>
      </Book>
    </Catalog>
    

    Note

    The Value property refers to the first XML element in a collection. If there is more than one element that has the same name in a collection, setting the Value property affects only the first element in the collection.

To add an attribute to an XML literal

  1. To add an attribute to an XML literal, first obtain a reference to the XML literal. You can then add an attribute by adding a new XML attribute axis property. You can also add a new XAttribute object to the XML literal by using the Add method. The following example shows both options.

    VB
    Dim newAttribute = "editorEmail"
    Dim editorID = "someone@example.com"
    For Each book In From element In catalog.<Catalog>.<Book>
      ' Add an attribute by using an XML attribute axis property.
      book.@genre = "Computer"
    
      ' Add an attribute to the Attributes collection.
      book.Add(New XAttribute(newAttribute, editorID))
    Next
    

    The following shows sample source XML and modified XML from this code example.

    Source XML:

    XML
    <?xml version="1.0"?>
    <Catalog>
      <Book id="bk101" >
        <Author>Garghentini, Davide</Author>
        <Title>XML Developer's Guide</Title>
        <Price>44.95</Price>
      </Book>
      <Book id="bk331">
        <Author>Spencer, Phil</Author>
        <Title>Developing Applications with Visual Basic .NET</Title>
        <Price>45.95</Price>
      </Book>
    </Catalog>
    

    Modified XML:

    XML
    <?xml version="1.0"?>
    <Catalog>
      <Book id="bk101" genre="Computer" editorEmail="someone@example.com">
        <Author>Garghentini, Davide</Author>
        <Title>XML Developer's Guide</Title>
        <Price>44.95</Price>
      </Book>
      <Book id="bk331" genre="Computer" editorEmail="someone@example.com">
        <Author>Spencer, Phil</Author>
        <Title>Developing Applications with Visual Basic .NET</Title>
        <Price>45.95</Price>
      </Book>
    </Catalog>
    

    For more information about XML attribute axis properties, see XML Attribute Axis Property.

To add an element to an XML literal

  1. To add an element to an XML literal, first obtain a reference to the XML literal. You can then add a new XElement object as the last sub-element of the element by using the Add method. You can add a new XElement object as the first sub-element by using the AddFirst method.

    To add a new element in a specific location relative to other sub-elements, first obtain a reference to an adjacent sub-element. You can then add the new XElement object before the adjacent sub-element by using the AddBeforeSelf method. You can also add the new XElement object after the adjacent sub-element by using the AddAfterSelf method.

    The following example shows examples of each of these techniques.

    VB
    Dim vbBook = From book In catalog.<Catalog>.<Book> 
                 Where book.<Title>.Value = 
                   "Developing Applications with Visual Basic .NET"
    
    vbBook(0).AddFirst(<Publisher>Microsoft Press</Publisher>)
    
    vbBook(0).Add(<PublishDate>2005-2-14</PublishDate>)
    
    vbBook(0).AddAfterSelf(<Book id="bk999"></Book>)
    
    vbBook(0).AddBeforeSelf(<Book id="bk000"></Book>)
    

    The following shows sample source XML and modified XML from this code example.

    Source XML:

    XML
    <?xml version="1.0"?>
    <Catalog>
      <Book id="bk101" >
        <Author>Garghentini, Davide</Author>
        <Title>XML Developer's Guide</Title>
        <Price>44.95</Price>
      </Book>
      <Book id="bk331">
        <Author>Spencer, Phil</Author>
        <Title>Developing Applications with Visual Basic .NET</Title>
        <Price>45.95</Price>
      </Book>
    </Catalog>
    

    Modified XML:

    XML
    <?xml version="1.0"?>
    <Catalog>
      <Book id="bk101" >
        <Author>Garghentini, Davide</Author>
        <Title>XML Developer's Guide</Title>
        <Price>44.95</Price>
      </Book>
      <Book id="bk000"></Book>
      <Book id="bk331">
        <Publisher>Microsoft Press</Publisher>
        <Author>Spencer, Phil</Author>
        <Title>Developing Applications with Visual Basic .NET</Title>
        <Price>45.95</Price>
        <PublishDate>2005-2-14</PublishDate>
      </Book>
      <Book id="bk999"></Book>
    </Catalog>
    

To remove an element or attribute from an XML literal

  1. To remove an element or an attribute from an XML literal, obtain a reference to the element or attribute and call the Remove method, as shown in the following example.

    VB
    For Each book In From element In catalog.<Catalog>.<Book>
      book.Attributes("genre").Remove()
    Next
    
    For Each book In From element In catalog.<Catalog>.<Book> 
                     Where element.@id = "bk999"
      book.Remove()
    Next
    

    The following shows sample source XML and modified XML from this code example.

    Source XML:

    XML
    <?xml version="1.0"?>
    <Catalog>
      <Book id="bk101" genre="Computer" editorEmail="someone@example.com">
        <Author>Garghentini, Davide</Author>
        <Title>XML Developer's Guide</Title>
        <Price>44.95</Price>
      </Book>
      <Book id="bk000"></Book>
      <Book id="bk331" genre="Computer" editorEmail="someone@example.com">
        <Author>Spencer, Phil</Author>
        <Title>Developing Applications with Visual Basic .NET</Title>
        <Price>45.95</Price>
      </Book>
      <Book id="bk999"></Book>
    </Catalog>
    

    Modified XML:

    XML
    <?xml version="1.0"?>
    <Catalog>
      <Book id="bk101" editorEmail="someone@example.com">
        <Author>Garghentini, Davide</Author>
        <Title>XML Developer's Guide</Title>
        <Price>44.95</Price>
      </Book>
      <Book id="bk000"></Book>
      <Book id="bk331" editorEmail="someone@example.com">
        <Author>Spencer, Phil</Author>
        <Title>Developing Applications with Visual Basic .NET</Title>
        <Price>45.95</Price>
      </Book></Catalog>
    

    To remove all elements or attributes from an XML literal, obtain a reference to the XML literal and call the RemoveAll method.

To modify an XML literal

  1. To change the name of an XML element, first obtain a reference to the element. You can then create a new XElement object that has a new name and pass the new XElement object to the ReplaceWith method of the existing XElement object.

    If the element that you are replacing has sub-elements that must be preserved, set the value of the new XElement object to the Nodes property of the existing element. This will set the value of the new element to the inner XML of the existing element. Otherwise, you can set the value of the new element to the Value property of the existing element.

    The following code example replaces all <Description> elements with an <Abstract> element. The content of the <Description> element is preserved in the new <Abstract> element by using the Nodes property of the <Description> XElement object.

    VB
    For Each desc In From element In catalog.<Catalog>.<Book>.<Description>
      ' Replace and preserve inner XML.
      desc.ReplaceWith(<Abstract><%= desc.Nodes %></Abstract>)
    Next
    
    For Each price In From element In catalog.<Catalog>.<Book>.<Price>
      ' Replace with text value.
      price.ReplaceWith(<MSRP><%= price.Value %></MSRP>)
    Next
    

    The following shows sample source XML and modified XML from this code example.

    Source XML:

    XML
    <?xml version="1.0"?>
    <Catalog>
      <Book id="bk101">
        <Author>Garghentini, Davide</Author>
        <Title>XML Developer's Guide</Title>
        <Price>44.95</Price>
        <Description>
          An in-depth look at creating applications
          with <technology>XML</technology>. For
          <audience>beginners</audience> or
          <audience>advanced</audience> developers.
        </Description>
      </Book>
      <Book id="bk331">
        <Author>Spencer, Phil</Author>
        <Title>Developing Applications with Visual Basic .NET</Title>
        <Price>45.95</Price>
        <Description>
          Get the expert insights, practical code samples, and best
          practices you need to advance your expertise with
          <technology>Visual Basic .NET</technology>.
          Learn how to create faster, more reliable applications
          based on professional, pragmatic guidance by today's top
          <audience>developers</audience>.
        </Description>
      </Book>
    </Catalog>
    

    Modified XML:

    XML
    <?xml version="1.0"?>
    <Catalog>
      <Book id="bk101">
        <Author>Garghentini, Davide</Author>
        <Title>XML Developer's Guide</Title>
        <MSRP>44.95</MSRP>    <Abstract>
          An in-depth look at creating applications
          with <technology>XML</technology>. For
          <audience>beginners</audience> or
          <audience>advanced</audience> developers.
        </Abstract>
      </Book>
      <Book id="bk331">
        <Author>Spencer, Phil</Author>
        <Title>Developing Applications with Visual Basic .NET</Title>
        <MSRP>45.95</MSRP>    <Abstract>
          Get the expert insights, practical code samples, and best
          practices you need to advance your expertise with
          <technology>Visual Basic .NET</technology>.
          Learn how to create faster, more reliable applications
          based on professional, pragmatic guidance by today's top
          <audience>developers</audience>.
        </Abstract>
      </Book>
    </Catalog>
    

See also

Accessing XML in Visual Basic

Visual Basic provides XML axis properties for accessing and navigating LINQ to XML structures. These properties use a special syntax to enable you to access elements and attributes by specifying the XML names.

The following table lists the language features that enable you to access XML elements and attributes in Visual Basic.

XML Axis Properties

Property description Example Description
child axis contact.<phone> Gets all phone elements that are child elements of the contact element.
attribute axis phone.@type Gets all type attributes of the phone element.
descendant axis contacts...<name> Gets all name elements of the contacts element, regardless of how deep in the hierarchy they occur.
extension indexer contacts...<name>(0) Gets the first name element from the sequence.
value contacts...<name>.Value Gets the string representation of the first object in the sequence, or Nothing if the sequence is empty.

Related Sections

XML Axis Properties
Provides links to sections describing the various XML access properties.

Overview of LINQ to XML in Visual Basic
Provides an introduction to using LINQ to XML in Visual Basic.

Creating XML in Visual Basic
Provides an introduction to using XML literals in Visual Basic.

Manipulating XML in Visual Basic
Provides links to sections about loading and modifying XML in Visual Basic.

XML
Provides links to sections describing how to use LINQ to XML in Visual Basic.

How to: Access XML Descendant Elements

This example shows how to use a descendant axis property to access all XML elements that have a specified name and that are contained under an XML element. In particular, it uses the Value property to get the value of the first element in the collection that the name descendant axis property returns. The name descendant axis property gets all elements named name that are contained in the contacts object. This example also uses the phone descendant axis property to access all descendants named phone that are contained in the contacts object.

Example

VB
Dim contacts As XElement = 
<contacts>
    <contact>
        <name>Patrick Hines</name>
        <phone type="home">206-555-0144</phone>
        <phone type="work">425-555-0145</phone>
    </contact>
</contacts>

Console.WriteLine("Name: " & contacts...<name>.Value)

Dim phoneTypes As XElement = 
  <phoneTypes>
      <%= From phone In contacts...<phone> 
          Select <type><%= phone.@type %></type> 
      %>
  </phoneTypes>

Console.WriteLine(phoneTypes)

Compiling the Code

This example requires:

See also

How to: Access XML Child Elements

This example shows how to use a child axis property to access all XML child elements that have a specified name in an XML element. In particular, it uses the Value property to get the value of the first element in the collection that the name child axis property returns. The name child axis property gets all child elements named phone in the contact object. This example also uses the phone child axis property to access all child elements named phone that are contained in the contact object.

Example

VB
Dim contact As XElement = 
<contact>
    <name>Patrick Hines</name>
    <phone type="home">206-555-0144</phone>
    <phone type="work">425-555-0145</phone>
</contact>

Console.WriteLine("Contact name: " & contact.<name>.Value)

Dim phoneTypes As XElement = 
  <phoneTypes>
      <%= From phone In contact.<phone> 
          Select <type><%= phone.@type %></type> 
      %>
  </phoneTypes>

Console.WriteLine(phoneTypes)

Compiling the Code

This example requires:

See also

How to: Access XML Attributes

This example shows how to use an attribute axis property to access XML attributes in an XML element by name. In particular, it uses the type attribute axis property to access the attribute named type in the phone object.

Example

VB
Dim phone As XElement = <phone type="home">206-555-0144</phone>

Console.WriteLine("Type: " & phone.@type)

See also

How to: Declare and Use XML Namespace Prefixes

This example shows how to import the XML namespace prefix ns and use it in an XML literal and XML axis properties.

Example

VB
' Place Imports statements at the top of your program.  
Imports <xmlns:ns="http://SomeNamespace">

Module Sample1

    Sub SampleTransform()

        ' Create test by using a global XML namespace prefix. 

        Dim contact = 
            <ns:contact>
                <ns:name>Patrick Hines</ns:name>
                <ns:phone ns:type="home">206-555-0144</ns:phone>
                <ns:phone ns:type="work">425-555-0145</ns:phone>
            </ns:contact>

        Dim phoneTypes = 
          <phoneTypes>
              <%= From phone In contact.<ns:phone> 
                  Select <type><%= phone.@ns:type %></type> 
              %>
          </phoneTypes>

        Console.WriteLine(phoneTypes)
    End Sub

End Module

Compiling the Code

This example requires:

See also

Source/Reference


©sideway

ID: 201000011 Last Updated: 10/11/2020 Revision: 0 Ref:

close

References

  1. Active Server Pages,  , http://msdn.microsoft.com/en-us/library/aa286483.aspx
  2. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929%28v=vs.90%29.aspx
  3. ASP Best Practices,  , http://technet.microsoft.com/en-us/library/cc939157.aspx
  4. ASP Built-in Objects,  , http://msdn.microsoft.com/en-us/library/ie/ms524716(v=vs.90).aspx
  5. Response Object,  , http://msdn.microsoft.com/en-us/library/ms525405(v=vs.90).aspx
  6. Request Object,  , http://msdn.microsoft.com/en-us/library/ms524948(v=vs.90).aspx
  7. Server Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525541(v=vs.90).aspx
  8. Application Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525360(v=vs.90).aspx
  9. Session Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms524319(8v=vs.90).aspx
  10. ASPError Object,  , http://msdn.microsoft.com/en-us/library/ms524942(v=vs.90).aspx
  11. ObjectContext Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525667(v=vs.90).aspx
  12. Debugging Global.asa Files,  , http://msdn.microsoft.com/en-us/library/aa291249(v=vs.71).aspx
  13. How to: Debug Global.asa files,  , http://msdn.microsoft.com/en-us/library/ms241868(v=vs.80).aspx
  14. Calling COM Components from ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524620(v=VS.90).aspx
  15. IIS ASP Scripting Reference,  , http://msdn.microsoft.com/en-us/library/ms524664(v=vs.90).aspx
  16. ASP Keywords,  , http://msdn.microsoft.com/en-us/library/ms524672(v=vs.90).aspx
  17. Creating Simple ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524741(v=vs.90).aspx
  18. Including Files in ASP Applications,  , http://msdn.microsoft.com/en-us/library/ms524876(v=vs.90).aspx
  19. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929(v=vs.90).aspx
  20. FileSystemObject Object,  , http://msdn.microsoft.com/en-us/library/z9ty6h50(v=vs.84).aspx
  21. http://msdn.microsoft.com/en-us/library/windows/desktop/ms675944(v=vs.85).aspx,  , ADO Object Model
  22. ADO Fundamentals,  , http://msdn.microsoft.com/en-us/library/windows/desktop/ms680928(v=vs.85).aspx
close

Latest Updated LinksValid XHTML 1.0 Transitional Valid CSS!Nu Html Checker Firefox53 Chromena IExplorerna
IMAGE

Home 5

Business

Management

HBR 3

Information

Recreation

Hobbies 8

Culture

Chinese 1097

English 339

Reference 79

Computer

Hardware 249

Software

Application 213

Digitization 32

Latex 52

Manim 205

KB 1

Numeric 19

Programming

Web 289

Unicode 504

HTML 66

CSS 65

SVG 46

ASP.NET 270

OS 429

DeskTop 7

Python 72

Knowledge

Mathematics

Formulas 8

Algebra 84

Number Theory 206

Trigonometry 31

Geometry 34

Coordinate Geometry 2

Calculus 67

Complex Analysis 21

Engineering

Tables 8

Mechanical

Mechanics 1

Rigid Bodies

Statics 92

Dynamics 37

Fluid 5

Fluid Kinematics 5

Control

Process Control 1

Acoustics 19

FiniteElement 2

Natural Sciences

Matter 1

Electric 27

Biology 1

Geography 1


Copyright © 2000-2024 Sideway . All rights reserved Disclaimers last modified on 06 September 2019