How to: Load XML from a File, String, or Stream (Visual Basic)
You can create XML Literals (Visual Basic) 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 Customizing Development 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
- To populate an XML literal such as an XElement or XDocument object from a stream, you can use the Load method or the XNode.ReadFrom method.
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)