Share via


How to: Load XML from a File, String, or Stream (Visual Basic)

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 Visual Studio Settings.

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.

    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.

    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.

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

Reference

XDocument.Load

XElement.Load

XElement.Parse

XDocument.Parse

XNode.ReadFrom

Other Resources

XML Literals

XML in Visual Basic

Manipulating XML in Visual Basic