XPath Querying over DataSets with the datasetnavigator - Arpan Desai

xiaoxiao2021-03-06  76

Summary: Arpan Desai discusses the DataSetNavigator, which provides the power and flexibility of the XML programming model without the overhead of having to convert the entire DataSet into an XmlDataDocument object (7 printed pages).

Click Here to Download The Code Sample for this Article.

Introduction

For A While Now, Dare Has Been Asking Me To Write An Article for Msdn. Now That Microsoft Visual Studio 2005 Beta 1 HAS (FINAL) SHIPPED, I'VE Managed to Find Some Time To Write to Tinker Around with An IDEA I'VE Had for a while: an xpathnavigator over a dataset.

The XmlDataDocument was originally envisioned as a component which allowed users to have an editable, hierarchical view of Microsoft ADO.NET DataSet data. The main use case has been the ability to perform an XSLT transformation over a DataSet in order to generate HTML for presentation on A WebPage. Unfortunately, The Performance of The XmldAdocument IS OFTEN A Bottleneck During Xslt Processing.

One of the workarounds to this issue is to utilize the WriteXml () method on the DataSet and load the serialized contents into the XmlDocument or XPathDocument class. Although performance typically improves using this method, it is still non-optimal due to the need to serialize and reparse the XML data. in addition, the data being transformed or queried is now residing in both the DataSet and the XmlDocument / XpathDocument, which means a substantial increase in memory usage. The ideal solution would have the performance of a native XML store such As The XpathDocument While Having Minimal Memory Overhead.

This Article Describes An Implementation of a Class Called The DatasetNavigator, Which Attempts To Solve this Problem in an ideal manner.

Building an XPath Navigator over the DataSetThe XPathNavigator is a read-only cursor over XML data sources. An XML cursor acts like a lens that focuses on one XML node at a time, but unlike pull-based APIs like the XmlReader, the cursor can be positioned anywhere along the XML document at any given time. The XPathNavigator is a good candidate for implementing an XML façade over non-XML data because it allows one to construct the XML views of a data source in a just-in-time manner, without Having to control the entire data source to an xml tree.

With the appropriate implementation, you could use it to query the file system, the Windows registry, an Active Directory store, or any other kind of hierarchical data store. In a previous article Steve Saxon created an XPathNavigator over object graphs using the ObjectXPathNavigator.

The XslTransform class in the Microsoft .NET Framework utilizes the XPathNavigator to perform XSLT processing over these sources. In addition, the XPathNavigator API also enables XPath querying. By implementing the DataSetNavigator, we can perform both XSLT transformations and XPath queries over the contents of a DataSet.

A question which must be asked is this:?. Why would the implementation of the DataSetNavigator be any faster than the XmlDataDocument One of the fundamental reasons why the XmlDataDocument has performance issues is its ability to be editable Anytime a change occurs in an instance of the XmlDataDocument, the change propagates to the DataSet it is associated with. Conversely, any change to the DataSet synchronizes the attached XmlDataDocument. Even when changes are not being made, the overhead of such a design prevents optimal performance during query or transformation. In both these Scenarios, There is no need for editing; therefore we can create a more omitting the overhead of the synchronizing functionality.the DataSetnavigator Implementation Details

The objective is quite simple:. Make a fast, lightweight XPathNavigator implementation on top of a DataSet The most complex feature that will be implemented is the ability to understand nested relationships within the DataSet so that hierarchies can be represented by means of the DataSetNavigator.

The first step in implementing the DataSetNavigator is understanding how the underlying data source will be modeled by the XPathNavigator. When no XML schema is provided to the DataSet, the rules used by the XmlDataDocument and the WriteXml () method to generate XML are quite simple.

The name of the DataSet is the root element in the XML. The rows of any tables that are not children in a nested relationship become the child elements of the root element. The columns of the tables become child elements within each row element. If there Are Any Nested Child Rows, Those Also Become Child Elements of The Row Element.

Conceptually, the implementation of the DataSetNavigator consists of two main parts. The first part is the ability to generate a simple tree, based on the contents of a DataSet. The second part is the ability to navigate this tree by implementing an XPathNavigator. In the implementation provided, the DataSetNavigator generates the tree when it is instantiated by a user, which results in a higher upfront cost to creating a DataSetNavigator but a much lower cost during actual use.The tree is constructed from a series of nodes, all of which derive From The DatasetNode Class. The Abstract DataSetnode Class Has The Basic Navigation Required to Traverse The Generated Tree and Has A Few MEGENERS OF IMPORTANCE:

parent-The parent member points to the parent DataSetNode of the current node. children-The children member is an array of DataSetNodes that represents the children of the current node. siblingPosition-The siblingPosition member represents the zero-based index of the current node position relative to its siblings. This is necessary so moving between siblings can be implemented simply and efficiently. localName-The localName member points to an atomized string which is the local name of the current node. XPathNavigators utilize the XmlNameTable for atomization and exposure of the local .

Our actual tree is built from specialized classes which are derived from DataSetNode These specialized classes correspond to the different types of positions the DataSetNavigator abstracts from the DataSet Based on the XML serialization rules stated above, we can have three position types of interest:.. TopNode -This is the top level element node exposed by the XPathNavigator that is positioned on a DataSet. TableRowNode-This element node is positioned on individual rows within the DataSet. ColumnRowNode-This element node is positioned on a specific column on a specific row.

These three node types cover the different positions available within the DataSet. There are two additional DataSetNode derived types that do not represent positions in a DataSet, but are necessary to finish off the DataSetNavigator.

RootNode-Every document has a root;. This node is an extremely simple node type which represents this root CellValueNode-We need a way to represent the actual data that resides in the DataSet Every ColumnRowNode in the tree has a single CellValueNode child that contains. THIS DATA. NOTE That The Implement of CellvaluEnode Does NOT IN The Duplication of Data Already in The Dataset, But INSTAT RETURns The Dataset Instances.

USAGE

Usage of the datasetnavigator is similar to any other xpathnavigator. The datasenetnavigator can be passed to the xsltransform class in The Example Below:

Dataset mydataset = new dataset ();

...

DataSetnavigator Mynavigator = New DataSetnavigator (MyDataSet);

Xsltransform myTransform = new xsltransform ();

MyTransform.Load ("Transform.xsl");

MyTransform.Transform (MyNavigator, Null, Console.out);

Alternative, Xpath Queries Can Be Executed Against The DataSet As The Following Example Demonstrates: Using System

Using system.data;

USING SYSTEM.XML;

Using system.xml.xpath;

USING Microsoft.xml;

Public class datasetnavtest {

Public static dataset createDataSet () {

DataSet Custds = New Dataset ("Books");

DataTable ORDERSTABLE = Custds.Tables.Add ("Book");

Datacolumn Pkcol = ORDERSTABLE.COLUMNS.ADD ("BookID", TypeOf (int32));

ORDERSTABLE.COLUMNS.ADD ("Title", TypeOf (String));

ORDERSTABLE.COLUMNS.ADD ("Quantity", TypeOf (int));

ORDERSTABLE.COLUMNS.ADD ("Unitprice", TypeOf (Decimal);

ORDERSTABLE.COLUMNS.ADD ("Category", TypeOf (String);

ORDERSTABLE.PRIMARYKEY = New Datacolumn [] {pkcol};

ORDERSTABLE.ROWS.ADD (New Object [] {101,

"Quantum Physics for Beginners", 2, 50, "Science"});

ORDERSTABLE.ROWS.ADD (New Object [] {201,

"Repair Your Car with Twine", 100, 24.99, "Automotive"});

ORDERSTABLE.ROWS.ADD (New Object [] {301,

"The Secret of Life, The Universe and Everything", 42, 41.99, "Humor"});

Custds.acceptchanges ();

Return Custds;

}

Public static void main (String [] args) {

DataSet DS = CreateDataSet ();

Console.writeline (DS.GETXML ​​());

DataSetnavigator NAV = New DataSetnavigator (DS);

XpathNodeTeiterator it =

Nav.select ("/ Books / Book [(Unitprice * Quantity)> 1000]");

While (item.movenext ()) {

/ * Print Title and total price of order using xpath queries * /

String itemtotal =

iTer.current.evaluate ("Unitprice * Quantity"). TOSTRING ();

String itemtitle =

iTer.current.evaluate ("String (Title)). TOSTRING ();

Console.writeline (" {0} = {1}", itemtitle, itemtotal; / * Print Title and total price of order using dataset apis * /

DataSetnavigator Nav2 = (DataSetnavigator) ore.current.clone ();

DataRow Row = Nav2.GetDataRow ();

String itemtotal2 =

((DECIMAL) ROW ["Unitprice"]) * ((int) Row ["Quantity"]). TOSTRING ();

String itemtitle2 = row ["title"]. TOSTRING ();

Console.writeline ("- {0} = {1}", itemtitle2, itemtotal2);

}

}

}

The DataSetNavigator implements the IDataSetPosition interface in addition to being an XPathNavigator. This interface is designed to return the position within the DataSet where the current DataSetNavigator is positioned, which allows for advanced scenarios in which accessing the actual DataRows / DataColumns of the DataSet is necessary. The iDatasetPosition Exposed The getPositionType () Method That Returns An Enumeration Value of The Current State:

DataSetPosition.DataSet -The DataSetNavigator is positioned on the DataSet. Calling GetDataSet () will successfully return the current DataSet. Calling GetDataRow () or GetDataColumnIndex () will fail since the navigator is not positioned on a specific row or column. DataSetPosition.Row- The DataSetNavigator is current positioned on a specific DataRow. Calling GetDataSet () will return the DataSet of which the DataRow is currently part. Calling GetDataRow () will return the current DataRow. Calling GetDataColumnIndex () will result in an error. DataSetPosition.Cell- This denotes that the DataSetNavigator is positioned on a specific cell. A cell is considered to be an intersection of a single DataRow and a single DataColumn. Calling GetDataSet (), GetDataRow (), or GetDataColumnIndex () will all succeed in this case.Conclusion

In preliminary testing, the DataSetNavigator is anywhere from 2x-50x faster than running the same transformation on an XmlDataDocument, depending on the size of the data being transformed and the complexity of the stylesheet. The DataSetNavigator is also 2x-5x faster than the XmlDocument or XpathDocument Workaround Currently Available, Due to The Fact That Reparsing The Contents of The DataSet Does Not Occur.

The current DataSetNavigator is fairly simple and does not incorporate some interesting features. One feature that is lacking is the support for namespaces. The current methods is converting a DataSet to XML support namespaces to be serialized when they are associated with various parts of the DataSet. THE CURRENT DATASETNAVIGATOR DOESN 'THIS OFNATIONALITY WOULD BE FAIRLY Straightforward to Add and Has BEEN LEFT AS AN EXERCISE for the INTERESTED READER.

转载请注明原文地址:https://www.9cbs.com/read-122872.html

New Post(0)