Using a DataSet as XML

for RuBoard

Using a DataSet as XML

The final section for today deals with how you can simultaneously manipulate a DataSet both using the objects internal to the DataSet and as XML using the Document Object Model (DOM). It is appropriate that we finish today's lesson with this dual programming model because it represents perhaps the highest point of integration between the DataSet and XML.

The class that provides the integration between the DataSet and the DOM is the XmlDataDocument , found in the System.Xml namespace. The XmlDataDocument is derived from the XmlDocument class and as such contains the methods and properties used to represent an XML document in memory using the DOM.

Note

See the online documentation for more information on the members of the XmlDocument class.


The purpose of the XmlDataDocument is to provide developers with the option of manipulating DataSet data as if it were simply XML parsed into the node-based hierarchical structure of the DOM. This enables developers familiar with the Microsoft XML Parser (MSXML) to manipulate DataSet data in a familiar way. In addition, as you'll see, using the XmlDataDocument allows you to do things not possible with the DataSet alone.

The XmlDataDocument can be used in two different ways. First, you can pass a populated DataSet to its constructor and it will create the hierarchical node structure on the fly from the data in the DataSet . You can then use the methods of the XmlDataDocument to manipulate the data. For example, the code in Listing 7.9 loads an XmlDataDocument from the sales DataSet created in the previous section. The code then iterates through each Title element and prints the time period recorded for each.

Caution

When an XmlDataDocument is instantiated , it is a fully separate object managed by the runtime that may contain a complete copy of the data from the DataSet . The two objects are kept in sync using events, so keep in mind that if the DataSet contains a large amount of data, so too might the XmlDataDocument . The determination of whether data is copied from one to another relates to the complexity of the XML document. Although the rules for this are complex, in general, the more complex the XML data, the more data will be copied to the DataSet .


Listing 7.9 Manipulating a DataSet as XML. This listing shows how you can use the XmlDataDocument class to work with a DataSet as XML data.
 Dim salesXml As New XmlDataDocument(sales) Dim titles, timePeriods As XmlNodeList Dim title, timeP As XmlNode Dim dr As DataRow titles = salesXml.GetElementsByTagName("Title") For Each title In titles    Console.WriteLine(title.Attributes("ISBN").Value)   timePeriods = title.SelectNodes("TimePeriod")   For Each timeP In timePeriods      Console.WriteLine(timeP.Attributes("Date").Value)     dr = salesXml.GetRowFromElement(CType(timeP, XmlElement))     Console.WriteLine(dr.Item("TimePeriod_Id").ToString)   Next Next 
graphics/analysis.gif

As you can see from Listing 7.9 , the GetElementsByTagName method is used to retrieve all the Title elements from the document into an XmlNodeList . The list is then iterated and the ISBN is retrieved from the Attributes collection. The SelectNodes method of the XmlDataDocument is then used to retrieve another list of nodes using an XPath query that in this case simply retrieves the TimePeriod elements. In a similar way, the Date for each time period is printed along with the hidden TimePeriod_Id column accessible through the GetRowFromElement method. Note that this column can be accessed only by referencing the DataSet ; it isn't represented in the XML because it is hidden. The XmlDataDocument also exposes the reverse GetElementFromRow method that accepts a DataRow and returns the XmlElement that it represents in the XML.

Tip

Although the DataSet and XmlDataDocument are kept in sync using events, if new nodes are added to the XmlDataDocument that do not correspond to columns in the DataSet , the nodes will be added but will not be synchronized with the DataSet . However, if you attempt to add or remove columns to a table in the DataSet after it has been mapped to an XmlDataDocument , you'll receive an InvalidOperationException .


The second way to use the XmlDataDocument is to load the XML by using its Load method after inferring the schema using the exposed DataSet property as shown here.

 Dim sales As New DataSet() Dim salesXml As New XmlDataDocument() Dim xmlData As New FileStream("royalty.xml", FileMode.Open) salesXml.DataSet.InferXmlSchema(xmlData, Nothing) xmlData.Position = 0 salesXml.Load(xmlData) sales = salesXml.DataSet 

In this case, a FileStream object is created to read the XML document. The schema for the underlying DataSet is then created using the InferXmlSchema method. This must be done first, otherwise , as noted previously, the new nodes in the XmlDataDocument will not map to anything in the DataSet . After the stream is repositioned to the beginning, the Load method of the XmlDataDocument is used to load the XML. Of course, an alternative technique that could be used in this example is to simply call the ReadXml method and allow it to infer the schema.

Finally, the XmlDataDocument is most powerful when using functionality that is not available when simply using the DataSet . For example, the TransformDs method in Listing 7.10 uses the XmlDataDocument to transform the contents of a DataSet using an XSL stylesheet and save it to a file. This technique could be very useful, for example, if ComputeBooks wanted to create static HTML pages from its catalog in a nightly process.

Listing 7.10 Transforming a DataSet . This method transforms a DataSet with an XSL stylesheet using the XmlDataDocument and classes from the System.Xml and related namespaces.
 Public Sub TransformDs(ByRef ds As DataSet, ByVal xslFile As String, _   ByVal destFile As String)   Dim xmlData As XmlDataDocument   Dim xslTrans As New XslTransform()   Dim xmlWriter As XmlTextWriter   Try     ' Load the stylesheet and transform     xslTrans.Load(xslFile)   Catch e As Exception     Throw New Exception("Could not load file " & xslFile, e)     Return   End Try   Try     ' Create an XmlTextWriter to write to the file     xmlWriter = New XmlTextWriter(destFile, Nothing)     ' Populate the XmlDataDocument and do the transform     xmlData = New XmlDataDocument(ds)     xslTrans.Transform(xmlData.DocumentElement, Nothing, xmlWriter)   Catch e As Exception     Throw New Exception("Could not write to " & destFile, e)   Finally     xmlWriter.Close()   End Try End Sub 
graphics/analysis.gif

Although the ins and outs of XSL and transformations are better left to other books, notice in Listing 7.10 that the XslTransform object xslTrans first loads the stylesheet passed in as an argument using the Load method. After opening the destination file using an XmlTextWriter object, the XmlDataDocument object is populated by passing the DataSet as an argument to the constructor. The root node of the XmlDataDocument , in this case xmlData.DocumentElement , is then passed to the Transform method along with the XmlWriter used to output the results of the transformation. The Transform method navigates through an XML document using a cursor model, applying the stylesheet rules found in the XSL document.

for RuBoard


Sams Teach Yourself Ado. Net in 21 Days
Sams Teach Yourself ADO.NET in 21 Days
ISBN: 0672323869
EAN: 2147483647
Year: 2002
Pages: 158
Authors: Dan Fox

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