borderAndreaVB free resources for Visual Basic developersborder

borderAndreaVB Visual Basic and VB.NET source code resources - Copyright © 1999-2007 Andrea Tincaniborder

AndreaVB Home | News Home | Forum Home | Downloads | Register | Search | PM | Profile

Previous Topic (String Handling in Java)Next Topic (Have your Own ItemData in .NET ComboBox) New Topic Post Reply
AndreaVB OnLine : Articles and tutorials : Accessing and Manipulating XML Data in Microsoft .NET Framework
Poster Resource
ucertify
Level: Protégé

Registered: 13-09-2005
Posts: 8
icon Accessing and Manipulating XML Data in Microsoft .NET Framework

<p>
The Extensible Markup Language (XML) is a simple, flexible and portable markup language. It is the preferred standard of communication developed by the World Wide Web Consortium (W3C). The XML data comprises of both human-readable data and descriptions of that data, and contains text-based XML files. An example of a well-formed XML document has been described as under:
<p>
&lt;? xml version = "1.0" encoding = "UTF-8"?&gt;<br>
&lt;StudentRecords&gt;<br>      
&lt;Students&gt;<br>        
&lt;StudentID> SO100 &lt;/StudentID&gt;<br>      
&lt;StudentName&gt;John Trivolta &lt;/StudentName&gt;<br>        
&lt;StudentSubject&gt;Science &lt;/StudentSubject&gt;<br>    
&lt;/Students&gt;<br>
<p>    
&lt;Students>&gt;<br>      
&lt;StudentID &gt; SO101 &lt;/StudentID&gt;<br>        
&lt;StudentName&gt; Bruce Lee &lt;/StudentName&gt;<br>      
  &lt;StudentSubject&gt; Computer &lt;/StudentSubject&gt;<br>    
  &lt;/Students&gt; <br>
&lt;StudentRecords&gt;
<p>
An XML document is a well-formed text-based data and considered as a meta-language that can easily be edited and created with any text editor. Specific rules should be followed while writing XML document.
ˇXML describes document structures using markup tags '<' and '>'. <ul><li>The line "<? xml version = "1.0" encoding ="UTF-8" ?>" is an XML declaration line which is optional</li><li>This line denotes the XML specification of W3C, and uses the UTF-8 standard set of characters</li><li>The line starting with '<?' string and ending with '?>' string is called processing instruction that provides information to the application about the process of XML document</li><li>A well-formed XML document should contain a start tag and an end tag. For example, '<Students>' is a start tag that contains an end tag '</Students>'. Unlike HTML tags, XML tags are case-sensitive. For example, if a start tag is written as '<StudentID>', its corresponding end tag should be written as '</StudentID>', and not as '</studentid>' or '</STUDENTID></li><li>Unlike HTML, XML document has no predefined elements and attributes, but is specified according to the application or business requirements</li></ul>
<p>
An XML document contains an associated document type definition (DTD) or an XML schema. An XML schema describes the data and the relationship between the data within an XML document. Unlike an XML document, an XML schema describes the elements and attributes of an XML document including type information, and also validates XML documents.
<p>
<b>The XML Document Object Model</b>
<p>
The XML Document Object Model commonly known as XML DOM is a representation of XML document in memory. The DOM class does the work of reading, writing, and manipulating an XML document. An XML document is a tree-structured consisting of parent and child nodes. In the above example of XML document, <StudentRecords> is the parent node and <Students> is the immediate child node. When more than one nodes are at the same level or they have the same parent node is called as sibling. There are different node types in the XML DOM. They are as under:
<p>
<table border="1"><tr><td>DOM Node Type</td><td>Description</td></tr><tr><td>Document</td><td>It is also known as the document root that behaves like a container for all nodes.</td></tr></tr><td>Element</td><td>Represents the element nodes.</td></tr><tr><td>Attributes</td><td>Represents the attributes of an element node.</td></tr><tr><td>Comment</td><td>Represents the comment nodes.</td></tr><tr><td>Text</td><td>Represents the text that belongs to a particular node.</td></tr></table>
<p>
The XmlDocument object that is derived from the XmlNode class represents the root node or the document node. The XmlDocument class performs tasks such as loading and saving XML documents and is used to access all the nodes in the document. The XmlDocument object consists of Load, LoadXml and Save methods that loads and saves XML documents. The following code snippet written in Visual Basic .NET shows how to load an XML DOM using Load method:
<p>
Imports System
Imports SystemIO.
IOImports System.Xml
Module Module1
Sub Main()   Dim myDoc As New XmlDocument()
  MyDoc.Load("students.xml")
  Console.WriteLine(myDoc.InnerXml.ToString)
   Console.ReadLine() End Sub
End Module
<p>
The following code snippet written in Visual C# .NET shows how to load an XML DOM using Load method:
<p>
using System;
using System.IO;
using System.Xml;class Class1
{  
static void Main()
  {      
XmlDocument myDoc = new XmlDocument();    
   MyDoc.Load("students.xml");      
Console.WriteLine(myDoc.InnerXml.ToString);    
Console.ReadLine();  
}
}
The XmlReader class and the XmlWriter class derived from the System.Xml namespace are abstract base classes that parse and write XML data from streams or XML documents. In the following sub-headings these classes have been fully illustrated.
<p>
<b>The XmlReader Class</b>
<p>
The XmlReader class is an abstract class that provides fast, non-cacheable, forward only, and read-only access to XML data. The methods of the XmlReader class provide access to the elements and attributes of XML data. The XmlTextReader class derived from the XmlReader class implements the methods defined by the XmlReader class. The XmlValidating Reader is another class derived from the XmlReader class facilitates to read XML data and supports the document type definition (DTD) or schema validation.
<p>
The XmlTextReader class requires fast access to XML data, and therefore is not required to read the entire document into memory via the Document Object Model or DOM. The following are some of the properties and methods of the XmlTextReader class:
<p>
<table border="1"><tr><td>MemberName</td><td>Type</td><td>Description</td></tr><tr><td>AttributeCount</td><td>Property</td><td>Returns an integer value that specifies the number of attributes on the current node.</td></tr><tr><td>HasAttributes</td><td>Property</td><td>Returns true determining whether a node contains attributes.</td></tr><tr><td>HasValue</td><td>Property</td><td>Returns true determining whether the current node contains a value.</td></tr><tr><td>Depth</td><td>Property</td><td>Returns an integer value that specifies the depth of the current node in an XML document.</td></tr><tr><td>IsEmptyElement</td><td>Property</td><td>Returns true specifying whether the current node of the XML element is empty.</td></tr><tr><td>Item</td><td>Property</td><td>Specifies a string value to an attribute.</td></tr><tr><td>Value</td><td>Property</td><td>Specifies the value of the current node as text.</td></tr><tr><td>Name</td><td>Property</td><td>Specifies the name of the current node in an XML document.</td></tr><tr><td>IsStartElement()</td><td>Method</td><td>Checks whether the current element is a start element.</td></tr><tr><td>Read()</td><td>Method</td><td>Reads the next node from the XML document.</td></tr><tr><td>ReadAttributeValue()</td><td>Method</td><td>Reads the attribute value.</td></tr><tr><td>ReadString()</td><td>Method</td><td>Reads the text content of an element or node.</td></tr><tr><td>MoveToFirstAttribute()</td><td>Method</td><td>Moves the current node to the first attribute.</td></tr><tr><td>MoveToNextAttribute()</td><td>Method</td><td>Moves the current node to the next attribute.</td></tr></table>
<p>
The following code snippet written in Visual Basic .NET shows how to read data using the XmlTextReader class:
<p>
Dim readdata As New XmlTextReader("e:\students.xml")
While readdata.Read()
Select Case readdata.NodeType
     Case XmlNodeType.Element
       Console.Write("<" + readdata.Name)
     While readdata.MoveToNextAttribute()        
   Console.Write(" " & readdata.Name & "= ' " & _             readdata.Value & "' ")    
End While      
Console.Write(">")  
     If readdata.HasAttributes Then      
   While readdata.MoveToNextAttribute        
     Console.Write(" " & readdata.Value & " ")          
End While      
End If    
Case XmlNodeType.Text      
Console.Write(readdata.Value)    
Case XmlNodeType.EndElement      
Console.WriteLine(("</" & readdata.Name & ">"))
End Select
End While
<p>
The following code snippet written in Visual C# .NET shows how to read data using the XmlTextReader class:
<p>
XmlTextReader readdata = new XmlTextReader("e:\students.xml");
while (readdata.Read())
{  
switch (readdata.NodeType)
{    
case XmlNodeType.Element:      
Console.Write("<" + readdata.Name);      
while (readdata.MoveToNextAttribute())
       {      
Console.Write(" " + readdata.Name + "= '"            + readdata.Value + " '");  
      }      
Console.Write(">");    
  if (readdata.HasAttributes)  
    {        
while (readdata.MoveToNextAttribute)    
     {    
       Console.Write(" " + readdata.Value + " ");  
       }    
  }    
   break;  
    case XmlNodeType.Text:
      Console.Write(readdata.Value);
     break;  
   case XmlNodeType.EndElement:    
   Console.WriteLine(("</" + readdata.Name + ">"));  
     break;  
}
}
<p>
<b>The XmlWriter Class</b>
<p>
The XmlWriter class is an abstract class of the System.Xml namespace that creates streams and writes data to XML documents. The XmlWriter class performs tasks such as writing various documents into one output stream, encoding binary data, and managing, flushing and closing the output stream. The XmlTextWriter class derived from the XmlWriter class provides properties and methods for writing XML data to an output file, stream or console. The following are some of the properties and methods of the XmlTextWriter class:
<p>
<table border="1"><tr><td>Member Name</td><td>Type</td><td>Description</td></tr><tr><td>BaseStream</td><td>Property</td><td>Returns the stream to which the XmlTextWriter is writing.</td></tr><tr><td>Formatting</td><td>Property</td><td>Specifies the formatting of the output in either Indented or None form.</td></tr><tr><td>WriteState</td><td>Property</td><td>Specifies the state value of the writer that includes Start, Element, Attribute, Content, Prolog, and Closed.</td></tr><tr><td>WriteStartDocument()</td><td>Method</td><td>Writes the XML declaration <?xml version = "1.0" ?> to the start of the XML document.</td></tr><tr><td>WriteStartElement()</td><td>Method</td><td>Specifies the start tag of a specified element.</td></tr><tr><td>WriteEndElement()</td><td>Method</td><td>Specifies the end tag of a specified element.</td></tr><tr><td>WriteStartAttribute()</td><td>Method</td><td>Specifies the start of an attribute.</td></tr><tr><td>WriteEndAttribute()</td><td>Method</td><td>Specifies the end of an attribute.</td></tr></table>
<p>
The following code snippet written in Visual Basic .NET shows how to write data using the XmlTextWriter class:
<p>
Dim writedata As New XmlTextWriter("e:\students.xml", System.Text.Encoding.UTF-8)
writedata.Formatting = Formatting.Indented
writedata.WriteStartDocument(False)
writedata.WriteDocType("StudentRecords", Nothing, Nothing, Nothing)
writedata.WriteComment("This file represents a fragment of Employees" & "database")
writedata.WriteStartElement("StudentRecords")
writedata.WriteStartElement("Students", Nothing)
writedata.WriteElementString("StudentID", "SO100" )
writedata.WriteElementString("StudentName", "John Trivolta")
writedata.WriteElementString("StudentSubject", "Science")
writedata.WriteEndElement()
writedata.WriteEndElement()' Write the XML to file and close the textWriter
writedata.Flush()
textWriter.Close()
Console.WriteLine("Press <Enter> to exit")
Console.Read()
<p>
The following code snippet written in Visual C# .NET shows how to write data using the XmlTextWriter class:
<p>
XmlTextWriter writedata = new XmlTextWriter("e:\students.xml", System.Text.Encoding.UTF-8);
writedata.Formatting = Formatting.Indented;
writedata.WriteStartDocument(false);
writedata.WriteDocType("StudentRecords", null, null, null);
writedata.WriteComment("This file represents a fragment of Employees" + "database");
writedata.WriteStartElement("StudentRecords");
writedata.WriteStartElement("Students", null);writedata.WriteElementString("StudentID", "SO100" );
writedata.WriteElementString("StudentName", "John Trivolta");
writedata.WriteElementString("StudentSubject", "Science")
;writedata.WriteEndElement();
writedata.WriteEndElement();
<p>
// Write the XML to file and close the textWriter
writedata.Flush()
writedata.Close();
Console.WriteLine("Press <Enter> to exit");
Console.Read();
<p>
<b>The XML Path (XPath) Language</b>
<p>
XML Path or XPath language described by the W3C Standard is a query language for finding information in an XML document. XPath uses path expressions to select a set of nodes and to navigate through elements and attributes in an XML document. XPath also contains built-in standard functions to manipulate string, numeric, and boolean values, and to manipulate sequences and nodes. XPath also defines different types of nodes such as element, attribute, text, namespace, processing instruction, and comment of an XML document and the relationship between the nodes in a document.
<p>
The XPathNavigator class derived from the System.Xml.XPath namespace performs XPath queries on any data source such as an XML document, a database or a DataSet. An XPathNavigator object for an XML document can be created by using the CreateNavigator method of the XmlNode and XPathDocument classes that implement the IXPathNavigable interface. The CreateNavigator method returns an XPathNavigator object that can be used to perform XPath queries. The XPathNavigator object reads data from an XML document that enables forward and backward navigation within the nodes therefore providing random access to nodes. The XPathNavigator objects formed by XmlDocument objects can be edited whereas those formed by XPathDocument objects are read-only.
<p>
The following are the steps to perform XPath queries that uses some of the methods of the XPathNavigator class:
<p> <ol><li>A set of nodes should be selected first before performing XPath queries.</li><li>The Select method of the XPathNavigator object is used to select the set of nodes that returns an object of the XPathNodeIterator class.After obtaining the XPathNodeIterator object, it is then used to iterate through the selected nodes that can easily be navigable within them.</li><li>The XPathNavigator class also provides some additional methods besides the Select method for optimal performance such as SelectChildren, SelectAncestors, SelectDescendants, and IsDescendant methods. These methods except the IsDescendant method return an XPathNodeIterator object. The state or position of the XPathNavigator object does not get affected when these methods are called.</li><li>After selecting a set of nodes, the nodes can be navigated randomly by using the XPathNavigator object that provides various methods for navigation. The following describes the methods that navigate a set of nodes:</li><li> <p>
<table border="1"><tr><td>Method</td><td>Description</td></tr><tr><td>MoveTo()</td><td> Moves the XPathNavigator object to another node in the current position and returns a Boolean value indicating its movement.</td></tr><tr><td>MoveToNext()</td><td>Moves the XPathNavigator object to the next sibling of the current node.</td></tr><tr><td>MoveToPrevious()</td><td>Moves the XPathNavigator object to the previous sibling of the current node.</td></tr><tr><td>MoveToFirst()</td><td>Moves the XPathNavigator object to the first sibling of the current node.</td></tr><tr><td>MoveToFirstChild()</td><td>Moves the XPathNavigator object to the first child of the current node. The current node must be the root node or has child nodes.</td></tr><tr><td>MoveToParent()</td><td>Moves the XPathNavigator object to the parent node of the current node. The current node must not be the root node.</td></tr><tr><td>MoveToRoot()</td><td>Moves the XPathNavigator object to the root node.</td></tr><tr><td>MoveToId()</td><td>Moves the XPathNavigator object to the node that contains an ID attribute. The ID of the node must be specified.</td></tr></table>
<p> </li></ol> Additionally, the Evaluate method can be used to evaluate XPath expressions that returns required results, and also performs various calculations.
<p>
As the XML Document Object Model creates and manipulates an XML document, the XML Schema Object Model creates an XML schema. The following sub-heading is a description of the XML Schema Object Model or XML SOM.
<p>
<b>The XML Schema Object Model</b>
<p>
The structure of XML documents is based on rules that are specified in an XML Schema Definition (XSD) file also known as an XML Schema. An XSD file consists of the definitions of elements, attributes, and data types. XML Schema is used to create, define and validate the structure of XML documents. The structure of an XML document can be specified by the names of elements that are used in the XML documents, and the structure and types of elements that must be valid for a specific schema.
<p>
An XML schema is an XML file that has an .xsd file name extension and uses valid XML objects to describe the contents of XML document. The structure of the XML document can be created by using simpleType and complexType elements. A simpleType element is used to define built-in data types or existing simple types and contains no element or attribute.
<p>
A complexType element consists of elements and attributes.The XML Schema Object Model (SOM) derived from the System.Xml.Schema namespace consists of a set of classes that read the schema definition from a file and also create the schema definition files programmatically. When a schema is created, it needs to be validated and compiled before writing it to a file. The XML SOM can load and save valid XSD schemas from and to files. In-memory schemas can be created by using strongly typed classes. The XmlSchemaCollection class is used to cache and retrieve schemas, and the XmlValidatingReader class is used to validate XML instance documents.
<p>
After creating a schema definition file, the XML Schema Object Model is used to edit files, which is similar to the way that the XML DOM uses for editing files. For validating an XSD file, the Compile method of the XmlSchema class is used to verify whether the schema is semantically correct. During the validation process, a validation callback is used if the parser gives an error or a warning, and simultaneously the ValidationEventHandler event is raised for the semantic validation checking of XML Schema.
<p>
Additionally, the XmlSchema.Read method is used to load schemas from a file. The XML SOM is also used to read and write XSD language schemas from files or other sources using the XmlTextReader, XmlTextWriter, and XmlSchema classes. The following code example in Visual Basic .NET shows how to read XML Schema from a file and then to write the schema to a new file.
<p>
Imports System.IO
Imports System
Imports System.XmlImports System.Xml.
SchemaImports System.Text
<p>
Class ReadAndWriteFile  
Public Shared Sub Main()    
Try      
Dim readdata As New XmlTextReader("Students.xsd")
       Dim readwrite As XmlSchema = XmlSchema.Read(readdata, Nothing)  
      readwrite.Write(Console.Out)
       Console.WriteLine("Exit Now!")  
      Console.Read()    
   Dim file1 As New FileStream("NewFile.xsd", FileMode.Create, _           FileAccess.ReadWrite)
       Dim xmlWriter As New XmlTextWriter(file1, New UTF8Encoding())
        xmlwriter.Formatting = Formatting.Indented
       readwrite.Write(xmlwriter)
     Catch e As Exception  
    Console.WriteLine(e)    
End Try
  End Sub
End Class
<p>
The following code example in Visual C# .NET shows how to read XML Schema from a file and then to write the schema to a new file.
using System.IO;
using System;
using System.Xml;
using System.Xml.Schema;
using System.Text;
class ReadAndWriteFile
{
  public static void Main()
  {    
try  
   {       XmlTextReader readdata = new XmlTextReader("Students.xsd");
      XmlSchema readwrite = XmlSchema.Read(readdata, null);  
     readwrite.Write(Console.Out);       Console.WriteLine("Exit Now!");
      Console.Read();
      FileStream file1 = new FileStream("NewFile.xsd", FileMode.Create,          FileAccess.ReadWrite);
      XmlTextWriter xmlWriter = new XmlTextWriter(file1,          new UTF8Encoding());
        xmlwriter.Formatting = Formatting.Indented;
      readwrite.Write(xmlwriter);
     }
    catch (Exception e)  
   {    
  Console.WriteLine(e);  
  }  
}
}
<p>
After creating, reading and writing XML data of an XML document, and creating XML schemas, now comes the use of the XmlValidatingReader class to validate an XML document. The following sub-heading is a description of an XML validation.
<p>
<b>Summary</b>
<p> <ul><li>XML or Extensible Markup Language describes document structures using markup tags '<' and '>'. A well-formed XML document should contain a start tag and an end tag. Unlike HTML tags, XML tags are case-sensitive.</li><li>An XML document is a well-formed text-based data and considered as a meta-language that can easily be edited and created with any text editor. The XML data comprises of both human-readable data and descriptions of that data, and contains text-based XML files.</li><li>The XML Document Object Model commonly known as XML DOM is a representation of XML document in memory. The DOM class does the work of reading, writing, and manipulating an XML document.</li><li>The XmlDocument object derived from the XmlNode class represents the root node or the document node. The XmlDocument object consists of Load, LoadXml and Save methods that loads and saves XML documents.</li><li>The XmlTextReader class derived from the XmlReader class implements the methods defined by the XmlReader class. The XmlValidating Reader is another class derived from the XmlReader class facilitates to read XML data and supports the document type definition (DTD) or schema validation.</li><li>XML Path or XPath language is a query language for finding information in an XML document. XPath also contains built-in standard functions to manipulate string, numeric, and boolean values, and to manipulate sequences and nodes.</li><li>The structure of XML documents is based on rules that are specified in an XML Schema Definition (XSD) file also known as an XML Schema. An XSD file consists of the definitions of elements, attributes, and data types.</li><li>The XML Schema Object Model (SOM) derived from the System.Xml.Schema namespace consists of a set of classes that read the schema definition from a file and also create the schema definition files programmatically.</li><li>The XML SOM is also used to read and write XSD language schemas from files or other sources using the XmlTextReader, XmlTextWriter, and XmlSchema classes.</li><li>The XmlValidatingReader class derived from the XmlReader class provides the document type definition (DTD), the XML Data Reduced (XDR), and the XSD schema validation services for the validation of an XML document or a fragment of an XML document.</li><li>A DataSet stores data obtained from a data source such as a relational database or an XML document. A DataSet can either be in form typed or untyped.</li><li>ADO.NET writes the DataSet data as a DiffGram, which means that both the original and current versions of the rows are included. A DiffGram can be represented in the XML format and is used to store and preserve all versions of the data.</li></ul>

About the Author:
<p>
uCertify was formed in 1996 with an aim to offer high quality educational training software and services in the field of information technology to its customers. uCertify provides exam preparation solutions for the certification exams of Microsoft, CIW, CompTIA, Oracle, Sun and other leading IT vendors. To know more about uCertify, please visit <a href="http://www.ucertify.com/">http://www.ucertify.com/</a>





[Edited by ucertify on 18-05-2006 at 04:20 AM GMT]

[Edited by ucertify on 18-05-2006 at 05:21 AM GMT]

[Edited by ucertify on 24-05-2006 at 06:06 PM GMT]

18-05-2006 at 03:19 AM
View Profile Send Email to User Show All Posts Visit Homepage | Add Comment
AndreaVB OnLine : Articles and tutorials : Accessing and Manipulating XML Data in Microsoft .NET Framework
Previous Topic (String Handling in Java)Next Topic (Have your Own ItemData in .NET ComboBox)New Topic Post Reply
Surf To:


Not Logged In? Username: Password: Lost your password?
Partners: Download Actual Software | Free Software Download
borderAndreaVB free resources for Visual Basic developersborder

borderAndreaVB Visual Basic and VB.NET source code resources - Copyright © 1999-2007 Andrea Tincaniborder