- A Disconnected Database
- Parsing XML
- Generating XML
- Bridge to the DOM via XmlDataDocument
- Summary
Bridge to the DOM via XmlDataDocument
An interesting facet of the integration between ADO.NET and the XML in .NET is the bridge class named XmlDataDocument. XmlDataDocument adds the ability to synchronize with the DataSet to the base functionality of the XmlDocument class that handles the DOM API. This is useful for situations in which you want to retain the fully fidelity of fairly unstructured XML or when you want to efficiently use other XML APIs. A contrived example is shown in Listing 6.
Listing 6: XmlDataDocument Demo Code
using System; using System.Data; using System.Xml; using System.Xml.Xsl; namespace XmlDotNet { public class XmlDataDocDemo { public static void Main() { // load the DataSet from the PO document DataSet ds = new DataSet(); ds.ReadXml("PO.xml"); // synchronize DataSet with XmlDataDocument // and provide a IXPathNavigable source for the // transformation XmlDataDocument doc = new XmlDataDocument(ds); // load up the XSLT transformation document XslTransform xslt = new XslTransform(); xslt.Load("PO.xslt"); // configure a writer to pump output to the // console XmlTextWriter writer = new XmlTextWriter(Console.Out); writer.Formatting=Formatting.Indented; // transform the document and output to console xslt.Transform(doc, null, writer); Console.WriteLine(); } } }
We bring back the XSLT demo from the article "XML in .NET: XPathNavigator and XSLT" and use the DataSet as the loading vehicle. Listing 7 shows the XSLT document that transforms the nodes into a text table for the output in Listing 8. Because the XslTransform class requires an IXPathNavigable data source, use the XmlDataDocument that fits that interface requirement after passing the loaded DataSet as a parameter to its constructor.
Listing 7: PO.xslt XSLT Transformation Document
<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0"[ccc] xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> Purchase Order --------------------------- Number: <xsl:value-of select="//Number" /> Order Date: <xsl:value-of select="//OrderDate" /> Line Items --------------------------- <xsl:apply-templates select="//LineItem" /> </xsl:template> <xsl:template match="LineItem"> Name:<xsl:value-of select="@Name"/> Qty:<xsl:value-of select="@Qty"/> Price:<xsl:value-of select="@Price"/> </xsl:template> </xsl:stylesheet>
Listing 8: XmlDataDocument Demo Results
Purchase Order --------------------------- Number: 1001 Order Date: 8/12/01 Line Items --------------------------- Name:Computer Desk Qty:1 Price:499.99 Name:Monitor Qty:1 Price:299.99 Name:Computer Qty:1 Price:999.99 Name:Mouse Qty:1 Price:49.99