Using XML Data
In this tutorial you will learn about Using XML Data – XML Basics, Using XmlDocument Class, Treating XML as Relational Data, The Introduction, The database, Handle Data Errors – Handle Database Errors and Handling Multi-User Errors.
Using XML Data
In this section we shall see some of the features of XML with reference to the .NET Framwork. Some prior knowledge of xml is required for understanding this section. The following assemblies implement the core XML standards.:
1) System.Xml -Basci Xml Input and Output with XmlReader and XmlWriter, Dom with XmlNode and its subclasses, many utility classes
2) System.Xml.Schema – Constraint of XML via XML Schema with XmlSchemaObject and its sub classes
3) System.Xml.Serialization – Serialization to plain XMLSerializer
4) System.Xml.Xpath – Navigation of XML via XPathand XPath document, xPathDocument, XpathExpression, and XpathNavigator
5) System.Xml.Xsl – Transformation of XML document via a XSLTwith XSLTRansformation.
Most of the classes that help users work with XML are found in System.Xml NameSpace. Microsoft provides a XML parser (MSXML) while implementing DOM as against another standard based on simple API for XML which is known as SAX implementation. XMLReader is used to read XML documents and XMLWriter is used to write XML documents. Users can navigate inside the XML document by using SMLDocument and XMLNode. Users can use XMLSchema for working with XMLSchemas. XmlConvert which provide encoding and decoding features. XMLTransform class is used as a stylesheet. The most familiar object known be the DataSet.
The .NET Framework provides facilities using which users can read a xml file and store the information in a DataSet. Users can also navigate through the document and write the contents of a DataSet as a disk xml file.
Using XmlDocument Class
This class implements the W3C Document Object Model (DOM) Level 1 Core and the Core DOM Level 2. The DOM is an in-memory (cache) tree representation of an XML document and enables the navigation and editing of this document. Because XmlDocument implements the System.Xml.XPath.IXPathNavigable interface it can also be used as the source document for the System.Xml.Xsl.XslTransform class. The System.Xml.XmlDataDocument class extends XmlDocument and allows structured data to be stored, retrieved, and manipulated through a relational System.Data.DataSet. This class allows components to mix XML and relational views of the underlying data. The following example illustrates the creation of XmlDocument and also the process of using the Xpath to navigate through the xml document and extract information from the xml file. The lines of code for the program are given below:
In the above code an object of the class XmlDocument was created. A namespace was created using the XmlNamespaceManager class. XmlNodeList was used to traverse the document and extract the information from the file.
The following screen shot show the output of the program.
The xml File contents are given below:
Treating XML as Relational Data
A relational database consists of a set of tables, where each table is a set of records. A record in turn is a set of fields and each field is a pair field-name/field-value. All records in a particular table have the same number of fields with the same field-names.
The description of the database above suggests a simple nesting of fields inside records inside tables inside databases. Here is an example of a single database with two tables:
The format is verbose, since XML is verbose. On the other hand, it compresses well with standard compression tools. It is also easy to print the database (or a part of it) with standard XML browsers and a simple style sheet.
A relation can be modeled as a hierarchy with a depth of four levels: the database consists of a set of tables, which in turn consist of records, which in turn consist of fields.
We can model the database with a document node and its associated element node:
The name is arbitrary. The url is optional, but can be used to point to information about the database. The order of the tables is also arbitrary, since a relational database defines no ordering on them. Each table of the database is represented by an element node with the records as its children:
The name is the name of the table. The order of the records is arbitrary, since the relational data model defines no ordering on them. A record is also represented by an element node, with its fields as children:
The name is arbitrary, since the relational data model doesn’t define a name for a record type. However, in XML it cannot be omitted. One scheme is to re-use the name of the table, or, if the table has a name that is a plural, to use the singular form (`persons’ -> `person’, `parts’ -> `part’). The order of the fields is again immaterial. A field is represented as an element node with a data node as its only child:
If d is omitted, it means the value of the fields is the empty string. The value of t indicates the type of the value (such as string, number, boolean, date). [Should we give a complete list?] If the type attribute is omitted, the type is assumed to be `string.’ Null values are represented by the absence of the field. Note that this is different from leaving the field empty, which indicates that the field contains a string of length zero. Null values have special properties in relational databases. For example, two fields both with null values are not equal (in contrast to two fields with zero-length strings, which are).
Handle Data Errors
Handling Database Errors
Data Centric applications can generate many errors, the source of which lie outside the .NET application. These errors are usually generated by the database. For instance there may be a activity of insert row. If you are inserting a new row with out giving value for a row that has a not null constraint specified, then the Insert will fail. These types of errors are to be handled like any other errors by using the Try .. Catch Block. However the best practice will be to do the validations in the data-entry screens, in such a way that the errors are avoided.
The code given below shows how we can handle an error occurring when the UPDATE method of the data adapter is executed:
Private Sub UpdateDatabase()
Catch dbcx As Data.DBConcurrencyExceptionDim response As Windows.Forms.DialogResultresponse = MessageBox.Show(CreateMessage(CType(dbcx.Row, NorthwindDataSet.CustomersRow)), "Concurrency Exception", MessageBoxButtons.YesNo)ProcessDialogResult(response)
Catch ex As Exception
MsgBox("An error was thrown while attempting to update the database.")
A message box will pop up when an error Occurs. The user can also improve the error handling method, by tweaking up the code as under:
A message box will be used to display the different versions of the record to the user and will allow the user to choose whether to overwrite the record with the changes or cancel the edit. Once the user selects an option on the message box, the response is passed to the ProcessDialogResult method. The options given are either to overwrite the current record in the database with the proposed change or abandon the local changes and refresh the data table with the record currently in the database. If the user chooses yes, the Merge method of DataTable is called with the PreserveChanges argument set to true. This will cause the update attempt to be successful, because the original version of the record now matches the record in the database.
Handling Multi-User Errors
Concurrency violations are to be handled in the way described below:
The UPDATE the database command has to be executed from within a Try ….. Catch block. When the exception is raised, the catch statement’s Row property is to be inspected to determine the cause of the violation. At this point the code to resolve the issue is generally based on the business policy. Let us see the following lines of Code:
Catch ex As DBConcurrencyException
Dim customErrorMessage As String
customErrorMessage = "Concurrency violation" & vbCrLf
customErrorMessage += CType(ex.Row.Item(0), String)
‘Replace the above code with appropriate business logic
‘ to resolve the concurrency violation.
In this lesson we have learnt how to manipulate and consume data. In the lessons that follow we shall be studying the Web services available in VB.NET.