Programmatic XML

Team Fly 

Page 487

Programmatic XML

In .NET, an XML document can be loaded using the Load method (you pass an argument describing the source, which can be a disk file, a stream, an XMLReader, or a TextReader object). Or you can use the LoadXML method to load a literal string, or string variable, into your document.

Start a new VB.NET Windows project, and add these namespaces:

 Imports System.Xml Imports System.Xml.Xsl 

To see how to create an XML document, then load a literal string into it, type in the code in Listing 17.3.

LISTING 17:3 LOADING A LITERAL STRING INTO AN XML DOCUMENT

Private Sub Form1_Load(ByVal sender As System.Object, _
 ByVal e As System.EventArgs) Handles MyBase.Load

        Dim XMLdoc As XmlDocument

        Try

            XMLdoc = New XmlDocument
            XMLdoc.LoadXml(''<Cookie><Name>Francine Cerance</Name></Cookie>")
            Console.WriteLine(XMLdoc.DocumentElement.OuterXml)
            Console.WriteLine(XMLdoc.DocumentElement.InnerXml)

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

Here's the result when this code is executed:

 <Cookie><Name>Francine Cerance</Name></Cookie> <Name>Francine Cerance</Name> 

To see how to load XML from a file, make the following change to the previous example. Change LoadXml to Load, and replace the string argument with the path to an XML file:

 XMLdoc.Load("c:\books.xml") 

Press F5 and you'll see two long lines of data in the Output window. The only difference between these lines is that the first line includes the <catalog> tags because it displays the outer XML.

Team Fly 


Visual Basic  .NET Power Tools
Visual Basic .NET Power Tools
ISBN: 0782142427
EAN: 2147483647
Year: 2003
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net