Tải bản đầy đủ (.pdf) (82 trang)

C# .NET Web Developer''''s Guide phần 7 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (487.5 KB, 82 trang )

470 Chapter 9 • Working with XML
Figure 9.11 shows the program after you click Run XPath Queries.When
you click the button, the program does a number of queries against the per-
sonnel.xml file and writes the results into the listbox on the form. Figure 9.12
shows a portion of the XML contained in the personnel.xml file used to gen-
erate the queries.
Figure 9.12
Generating Queries (personnel.xml)
<?xml version="1.0" standalone="yes"?>
<Employees>
<Employee EmployeeID="1">
<FirstName>John</FirstName>
<MiddleInit>M</MiddleInit>
<LastName>Smith</LastName>
<Salaried>true</Salaried>
<Wage>40000</Wage>
<Active>true</Active>
<Title>Jr. Programmer</Title>
<Location>
<Address>103 N.72nd</Address>
<City>Seattle</City>
<State>WA</State>
<Zip>98103</Zip>
</Location>
</Employee>
<Employee EmployeeID="2">
<FirstName>Joe</FirstName>
<MiddleInit>R</MiddleInit>
<LastName>Jones</LastName>
<Salaried>false</Salaried>
<Wage>22.75</Wage>


<Active>true</Active>
<Title>Graphic Artist</Title>
<Location>
<Address>13222 S. 1st Avenue</Address>
<City>Portland</City>
www.syngress.com
Continued
Working with XML • Chapter 9 471
<State>OR</State>
<Zip>97206</Zip>
</Location>
</Employee>
Figure 9.13 contains the relevant portions of the source code for the XPath
sample. Source code inserted by the Visual Studio.NET designer has been omitted.
Figure 9.13 Relevant Portions of Source Code (XPathForm.cs)
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Xml;
using System.Xml.XPath;
using System.IO;
namespace XPath
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form

{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
www.syngress.com
Figure 9.12 Continued
Continued
472 Chapter 9 • Working with XML
private string m_strOutput;
public Form1()
{
InitializeComponent();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
/// <summary>
/// Called when Run XPath Queries is pressed
/// </summary>
private void button1_Click(object sender, System.EventArgs e)
{
Cursor currentCursor = Cursor.Current;

try
{
Cursor.Current = Cursors.WaitCursor;
// Do XPath queries on both XPath Documents and
// DOM-based XML documents
doXPathDocumentQueries();
doXmlDocumentQueries();
// Show results on-screen
www.syngress.com
Figure 9.13 Continued
Continued
Working with XML • Chapter 9 473
textBox1.Text = m_strOutput;
}
catch ( Exception exception )
{
MessageBox.Show( exception.Message );
}
finally
{
Cursor.Current = currentCursor;
}
}
/// <summary>
/// Do XPath queries against a read-only XPathDocument
/// </summary>
private void doXPathDocumentQueries()
{
m_strOutput =
"*** Beginning XPathDocument Queries ***\r\n\r\n";

// Load the XML document into a read-only XPathDocument
// and instantiate a navigator for queries.
XPathDocument doc = new XPathDocument( "personnel.xml" );
XPathNavigator navigator = doc.CreateNavigator();
m_strOutput += "*** Show All Wages ***\r\n\r\n";
// Find all Employee/Wage elements in the document and
// display the wage information on-screen
XPathNodeIterator iterator =
navigator.Select( "descendant::Employee/Wage" );
www.syngress.com
Figure 9.13 Continued
Continued
474 Chapter 9 • Working with XML
while ( iterator.MoveNext() )
{
m_strOutput += iterator.Current.Name + ": ";
m_strOutput += iterator.Current.Value + "\r\n";
}
m_strOutput +=
"\r\n\r\n*** Show All Employees in Seattle ***\r\n\r\n";
// Find all employees in the Seattle office and display
// their names on-screen
iterator =
navigator.Select( "//Employee[Location/Zip='98103']" );
while ( iterator.MoveNext() )
{
XPathNavigator nav2 = iterator.Current;
nav2.MoveToFirstChild();
m_strOutput += nav2.Value; // First name
nav2.MoveToNext();

m_strOutput += ". " + nav2.Value; // Middle init
nav2.MoveToNext();
m_strOutput += " " + nav2.Value + "\r\n"; // Last name
}
m_strOutput +=
"\r\n\r\n*** Salaried Employee Average Wage ***\r\n\r\n";
// Calculate the average salary for all salaried employees
// in the company and display on-screen
Int32 nAverage =
(Int32)(Double)navigator.Evaluate(
"sum(//Employee[Salaried='true']/Wage) div
www.syngress.com
Figure 9.13 Continued
Continued
Working with XML • Chapter 9 475
count(//Employee[Salaried='true'])" );
m_strOutput += "Average Salary: $" + nAverage.ToString();
}
/// <summary>
/// Do an XPath queries against a DOM-based XML document and
then
/// modify the document.
/// </summary>
private void doXmlDocumentQueries()
{
m_strOutput +=
"\r\n\r\n*** Beginning XML Document Query ***\r\n\r\n";
// Load the XML document into a DOM-based XML document
XmlDocument doc = new XmlDocument();
doc.Load( "personnel.xml" );

// Get a list of the Active element nodes for each employee
// in Portland
XmlNodeList nodeList =
doc.SelectNodes(
"//Employee[Location/Zip='97206']/Active");
foreach ( XmlNode node in nodeList )
{
// Mark each Portland employee as inactive
node.InnerText = "false";
}
// Display the modified document on-screen
StringWriter writerString = new StringWriter();
XmlTextWriter writer = new XmlTextWriter( writerString );
www.syngress.com
Figure 9.13 Continued
Continued
476 Chapter 9 • Working with XML
writer.Formatting = Formatting.Indented;
doc.WriteTo( writer );
writer.Flush();
m_strOutput += writerString.ToString();
}
}
}
The program runs through two sets of XPath queries against the personnel
.xml file.The first set of queries is against XML loaded into an object of type
System.Xml.XPath.XPathDocument.The XPathDocument class has been optimized
to work with XPath queries. It supports read-only access to the document. An
XPathNavigator class object is used to perform queries against an XPathDocument
document. Here is the code that instantiates and loads an XPathDocument with

XML from a disk file.An XPathNavigtor class object is instantiated to perform
XPath queries against the document:
XPathDocument doc = new XPathDocument( "personnel.xml" );
XPathNavigator navigator = doc.CreateNavigator();
The Select method of the XPathNavigator class is used to perform a query
against the XML document. It takes an XPath statement as an argument.The fol-
lowing query returns all of the <Wage> elements in the XML document:
XPathNodeIterator iterator =
navigator.Select( "descendant::Employee/Wage" );
while ( iterator.MoveNext() )
{
m_strOutput += iterator.Current.Name + ": ";
m_strOutput += iterator.Current.Value + "\r\n";
}
The select statement takes an XPath expression as an argument and returns an
XPathNodeIterator object, which is used to traverse the node list returned.The
Current property of XPathNodeIterator points to the current position in the node
list returned form the Select method call.The position is undefined until the first
www.syngress.com
Figure 9.13 Continued
Working with XML • Chapter 9 477
call to the MoveNext method. As each <Wage> element is encountered in the
returned node list, the element tag and value are saved for later display in the
listbox on-screen.The Name property of Current returns the element tag and the
Value property of Current returns the text contained within the <Wage> element.
The second query against the XPathDocument returns all the employees in the
Seattle office and displays their names. Here is the code to accomplish this:
www.syngress.com
XPath Expressions
A brief explanation of XPath statements is in order. XPath expressions

use what is termed a location path, which is made up of one or more
location steps that are separated by a “/” or by a “//”. The “/” character
indicates an absolute path, and the “//” characters indicate a relative
path from the current node. A location step contains an axis and a node
test, and it may contain predicates. The axis indicates the direction of
the query from the current node. Examples are child, ancestor, and
descendent. The node test is either the name of a node in the document,
the wildcard character(*), or one of several node tests such as node()
and text(). The predicate is used to filter the node test to pinpoint a spe-
cific set of nodes. A predicate is contained within brackets. Here are two
examples of XPath expressions:

In the XPath expression descendent::Employee/Wage,
descendent indicates the axis and Employee/Wage indicates
the node test. There is no predicate in this case. The expres-
sion returns the Employee/Wage descendents of the current
node.

In the XPath expression “//Employee[Location/Zip=’98103’],
the “//” indicates the axis, Employee indicates the node test
and [Location/Zip=’98103’] indicates the predicate. The
expression returns the Employee elements with a Location/Zip
element whose value is “98103”.
These are relatively simple examples. You can combine extremely
complex combinations of axes, node tests, and predicates to create
extremely powerful queries against XML documents using XPath.
Developing & Deploying…
478 Chapter 9 • Working with XML
iterator =
navigator.Select( "//Employee[Location/Zip='98103']" );

while ( iterator.MoveNext() )
{
XPathNavigator nav2 = iterator.Current;
nav2.MoveToFirstChild();
m_strOutput += nav2.Value; // First name
nav2.MoveToNext();
m_strOutput += ". " + nav2.Value; // Middle init
nav2.MoveToNext();
m_strOutput += " " + nav2.Value + "\r\n"; // Last name
}
The only real difference with this query is that you need to use a second
instance of XPathNavigator. Each node in the node list is an <Employee> ele-
ment.The second XPathNavigator object is needed so that you can maintain your
position in the node list of <Employee> elements.
The last query against the XPathDocument object does a summary query. It
returns a result, not a node list. Here is the code, which calculates the average
salary of all salaried employees:
Int32 nAverage =
(Int32)(Double)navigator.Evaluate(
"sum(//Employee[Salaried='true']/Wage) div
count(//Employee[Salaried='true'])" );
When performing summary queries, the Evaluate method is used instead of
the Select method. It also takes an XPath expression as an argument.You can see
from this example that the XPath expressions can get quite complex.
The second set of queries is done against an XmlDocument object. As we men-
tioned earlier, an XPathDocument is read-only. So, if you want to use XPath
directly against an XML document and update the document, you will need to
use an XmlDocument object. Here is the relevant code from the sample:
XmlDocument doc = new XmlDocument();
doc.Load( "personnel.xml" );

// Get a list of the Active element nodes for each employee
www.syngress.com
Working with XML • Chapter 9 479
// in Portland
XmlNodeList nodeList =
doc.SelectNodes( "//Employee[Location/Zip='97206']/Active");
foreach ( XmlNode node in nodeList )
{
// Mark each Portland employee as inactive
node.InnerText = "false";
}
This example simulates shutting down the Portland office.The <Active>
element is set to false for all employees in the Portland office. First, a new
XmlDocument object is instantiated and then loaded using the Load method. Next,
the XPath query against the document is executed using the SelectNodes method
of the System.Xml.Node class. It takes an XPath expression as an argument and
returns an XmlNodeList object. In this case, it is a node list containing each
<Active> element for each employee in the Portland office.The node list is tra-
versed using the foreach statement, and the text value associated with the
<Active> element is set to false. Assigning the string “false” to the InnerText prop-
erty accomplishes this.
Working with XSL
The previous section shows how XPath is used as a general query tool. In this sec-
tion, you will see XSLT used to transform XML documents to a different format.
XSL stylesheets will use XPath expressions to select node lists for transformation.
Our sample simulates a real-world scenario.The scenario is that the human
resources division of a company named EntegraTech maintains personnel data in
an XML file named personnel.xml. Another division of the company maintains a
Web site that includes some reports based on personnel information.The Web
site uses XSL stylesheets to build HTML Web pages from personnel information

contained in XML files. Unfortunately, the Web site stylesheets expect the XML
to be in a different format than the format in the personnel.xml file supplied by
the HR department.The sample code transforms the XML into the format that
the Web site stylesheets expect and then builds one of the HTML reports. XSL
stylesheets are used both to transform the XML and to create the HTML.
The sample requires the files personnel.xml, salariedpersonnel.xsl, and
salariedreport.xsl to be in the same directory the sample is run from.You can find
www.syngress.com
480 Chapter 9 • Working with XML
the files on the CD that accompanies this book, in the XSL directory.You may
need to copy the files to the directory you run the sample from.The full source
code for the sample is in the XSL directory as well.The file that contains the
source code is named XSLForm.cs. Figure 9.14 shows the running program.
Figure 9.14 shows the program after you click Run XSL Sample.When
you click the button, it transforms the personnel.xml file by using an XSL
stylesheet, displays the original XML file and the transformed XML file in the
listbox, and writes the transformed XML to another file on disk.The Show
HTML Report button then becomes active. Clicking the button runs a second
XSLT stylesheet, which creates a HTML document from the newly transformed
XML. Internet Explorer is then launched and displays the HTML report. Figure
9.15 shows the report displayed in Internet Explorer.
www.syngress.com
Figure 9.14 The XSL Sample Program
Figure 9.15 The EntegraTech HTML Report
Working with XML • Chapter 9 481
You have seen the structure of the personnel.xml file already. Figure 9.16
shows it again for comparison with the format expected by the Web site. Figure
9.17 shows the format of the XML expected by the Web site. Comparing these
two will help in understanding what the XSL stylesheet must do.
Figure 9.16

Partial Contents of the personnel.xml File
<Employees>
<Employee EmployeeID="1">
<FirstName>John</FirstName>
<MiddleInit>M</MiddleInit>
<LastName>Smith</LastName>
<Salaried>true</Salaried>
<Wage>40000</Wage>
<Active>true</Active>
<Title>Jr. Programmer</Title>
<Location>
<Address>103 N.72nd</Address>
<City>Seattle</City>
<State>WA</State>
<Zip>98103</Zip>
</Location>
</Employee>
Figure 9.17 XML Format Expected by the Web Site
<Salaried>
<Employee>
<Name>John M. Smith</Name>
<Wage>40000</Wage>
<Location>98103</Location>
</Employee>
As you can see, the XSL stylesheet needs to combine the <FirstName>,
<MiddleInit>, and <LastName> elements into a single <Name> element. It also
needs to copy the <Wage> element verbatim. Finally, it needs to copy the con-
tents of the <Zip> element into a <Location> element.
www.syngress.com
482 Chapter 9 • Working with XML

The file salariedpersonnel.xsl is the stylesheet that is used to convert from the
first XML representation to the second. It is shown in Figure 9.18.
Figure 9.18 The Stylesheet (salariedpersonnel.xsl)
<xsl:stylesheet version="1.0"
xmlns:xsl=" /><xsl:template match="/">
<Salaried>
<xsl:apply-templates/>
</Salaried>
</xsl:template>
<xsl:template match="Employees">
<xsl:apply-templates select="Employee[Salaried='true']"/>
</xsl:template>
<xsl:template match="Employee[Salaried='true']">
<Employee>
<Name>
<xsl:value-of select="FirstName"/><xsl:text> </xsl:text>
<xsl:value-of select="MiddleInit"/><xsl:text>. </xsl:text>
<xsl:value-of select="LastName"/>
</Name>
<Wage>
<xsl:value-of select="Wage"/>
</Wage>
<Location>
<xsl:value-of select="Location/Zip"/>
</Location>
</Employee>
</xsl:template>
</xsl:stylesheet>
www.syngress.com
Working with XML • Chapter 9 483

An XSL stylesheet uses pattern matching to process an XML document.The
XSLT processor begins processing the XML document and looks for statements
in the XSL script, called rules, which match nodes encountered in the XML doc-
ument. Near the top is the rule for the root element of the document:
<xsl:template match="/">
<Salaried>
<xsl:apply-templates/>
</Salaried>
</xsl:template>
When the root element of the original XML document is encountered, the
previous statements are executed. In this case, a <Salaried> element is created and
the child nodes of the root element are processed by the <xsl:apply-templates/>
statement.When the <Employees> element is encountered, execute the fol-
lowing statements:
<xsl:template match="Employees">
<xsl:apply-templates select="Employee[Salaried='true']"/>
</xsl:template>
The select attribute of an <xsl:apply-templates> statement contains the pattern
to match in an XML document.The pattern matching string can be an XPath
expression.This is where XPath comes into play in XSL stylesheet processing.
The preceding XSL script statements ignore any <Employee> elements that do
not contain a child element <Salaried> with a text node whose value is “true”. In
effect, you execute a rule that returns all <Employee> elements that represent
salaried employees and ignore all other nodes encountered in the XML document.
The following statements process the matching salaried employee elements:
<xsl:template match="Employee[Salaried='true']">
<Employee>
<Name>
<xsl:value-of select="FirstName"/><xsl:text> </xsl:text>
<xsl:value-of select="MiddleInit"/><xsl:text>. </xsl:text>

<xsl:value-of select="LastName"/>
</Name>
<Wage>
<xsl:value-of select="Wage"/>
www.syngress.com
484 Chapter 9 • Working with XML
</Wage>
<Location>
<xsl:value-of select="Location/Zip"/>
</Location>
</Employee>
</xsl:template>
These statements convert all salaried <Employee> elements in the original
XML document to the format required in the new XML document.This is
where the meat of the transformation takes place. Let’s take a look in Figure 9.19
at the relevant portions of the source code that perform the XSLT transformation.
Figure 9.19
XML-to-XML Transformation in the Source Code (XSLForm.cs)
private void doXMLToXMLTransform()
{
// Show the original document on-screen
m_strOutput = "*** personnel.xml - Original XML ***\r\n\r\n";
showXMLDocument( "personnel.xml" );
// Load the new document, apply an XSL tranformation to
// it and save the new document to disk
XPathDocument docXPath =
new XPathDocument( "personnel.xml" );
XslTransform xslTransform = new XslTransform();
XmlTextWriter writer =
new XmlTextWriter( "salaried.xml", null );

xslTransform.Load( "salariedpersonnel.xsl" );
xslTransform.Transform( docXPath, null, writer );
writer.Close();
m_strOutput +=
"*** salaried.xml - Transformed XML ***\r\n\r\n";
// Show the transformed document
www.syngress.com
Continued
Working with XML • Chapter 9 485
showXMLDocument( "salaried.xml" );
}
private void showXMLDocument( string strXMLFileName )
{
XmlDocument docDOM = new XmlDocument();
docDOM.Load( strXMLFileName );
StringWriter writerString = new StringWriter();
XmlTextWriter writer2 = new XmlTextWriter( writerString );
writer2.Formatting = Formatting.Indented;
docDOM.WriteTo( writer2 );
writer2.Flush();
m_strOutput += writerString.ToString() + "\r\n\r\n";
}
In the doXMLToXMLTransform method, an XPathDocument object is instanti-
ated and loaded with XML contained in the personnel.xml file.Then, an
XslTransform object is instantiated.The XslTransform object is the engine used to
perform XSLT transformations on XML documents in the .NET Framework.
After the transformation is complete, the results are written to a new XML
file on disk. An XmlTextWriter object is created that writes the transformed file to
disk.The file that is created is named salaried.xml, which is the first parameter
passed to the XmlTextWriter constructor.

The Load method of the XslTransform class loads the XSL stylesheet from
disk. Finally, the transform is executed by calling the Transform method of the
XslTransform class object. The Transform method takes the XML document object
and the text writer objects as parameters.The second parameter of the Transform
method is used to pass additional runtime arguments that are used in the
stylesheet. Because you have no runtime arguments, it is left null.After the trans-
form is complete, the XmlTextWriter object is closed to complete the writing of
the new XML document file to disk.
The showXMLDocument method is a helper function that reads an XML
document from disk and formats it with indenting for display purposes.The
showXMLDocument method illustrates how the XmlDocument, XmlTextWriter, and
www.syngress.com
Figure 9.19 Continued
486 Chapter 9 • Working with XML
StringWriter classes work together to convert an XML document on disk to an
in-memory string.
As you can see, very little source code is necessary to perform the complex
task of transforming an XML document to another format.You have now con-
verted the original document to the new format that is needed to generate the
HTML reports. Let’s take a look in Figure 9.20 at the XSL stylesheet used to
transform the converted XML to HTML.
Figure 9.20
The Stylesheet (salariedreport.xsl)
<xsl:stylesheet version="1.0"
xmlns:xsl=" /><xsl:template match="/">
<html>
<head>
<title>EntegraTech Salaried Employees</title>
</head>
<body bgcolor="#C0C0C0">

<h1 align="left">EntegraTech Salaried Employees</h1>
<p></p>
<xsl:apply-templates />
</body>
</html>
</xsl:template>
<xsl:template match="Salaried">
<h2 align="left">Seattle Office Salaried Employees</h2>
<table border="0" width="100%">
<xsl:apply-templates select="Employee[Location='98103']" />
</table>
<p></p>
<h2 align="left">Portland Office Salaried Employees</h2>
<table border="0" width="100%">
<xsl:apply-templates select="Employee[Location='97206']" />
</table>
</xsl:template>
www.syngress.com
Continued
Working with XML • Chapter 9 487
<xsl:template match="Employee[Location='98103']">
<tr>
<td width="28%">
<xsl:value-of select="Name" />
</td>
<td width="72%">
$<xsl:value-of select="Wage" />
</td>
</tr>
</xsl:template>

<xsl:template match="Employee[Location='97206']">
<tr>
<td width="28%">
<xsl:value-of select="Name" />
</td>
<td width="72%">
$<xsl:value-of select="Wage" />
</td>
</tr>
</xsl:template>
</xsl:stylesheet>
Briefly, this stylesheet creates an HTML document for display in a Web
browser.You can see the familiar pattern matching statements that we saw in the
previous stylesheet.This stylesheet creates two HTML tables that display the
names of employees and their wages.The first table shows the employees in the
Seattle office, and the second shows the employees in Portland. Figure 9.21 shows
the C# source code used to perform the transformation from XML to HTML.
www.syngress.com
Figure 9.20 Continued
488 Chapter 9 • Working with XML
Figure 9.21 XML to HTML Transformation in the Source Code (XSLForm.cs)
private void doXMLToHTMLTranformation()
{
// Load the XML document, apply an XSL transformation to it,
// resulting in HTML which is written to disk.
XPathDocument docXPath = new XPathDocument( "salaried.xml" );
XslTransform xslTransform = new XslTransform();
XmlTextWriter writer =
new XmlTextWriter( "salariedreport.html", null );
xslTransform.Load( "salariedreport.xsl" );

xslTransform.Transform( docXPath, null, writer );
writer.Close();
btnShowHTML.Enabled = true;
}
The code looks very similar to the code you saw that performed the XML-
to-XML transformation earlier in Figure 9.19 earlier in this section.The only
noticeable difference is that the XmlTextWriter object now takes the name of the
HTML file as a parameter.When the doXMLToHTMLTransformation method is
complete, a new HTML file exists named salariedreport.html, which contains the
report. Here is the source code that launches Internet Explorer and displays the
report in the Web browser:
private void btnShowHTML_Click_1(object sender,
System.EventArgs e)
{
System.Diagnostics.Process.Start("salariedreport.html");
}
The Start method of the System.Diagnostics.Process class executes a program.
This overloaded version of the Start method takes a document name. If the docu-
ment type has a file association established with a program on the computer, it
will invoke that program. In our case, HTML files are associated with Internet
Explorer. So, when the Start method is called with an HTML filename as the
parameter, Internet Explorer is launched and the HTML file passed in is dis-
played.
www.syngress.com
Working with XML • Chapter 9 489
www.syngress.com
XSLT: Debugging Stylesheets
XSLT is a powerful technology for transforming XML documents. The
XPath expressions used in XSL stylesheets to match nodes in an XML
document can be very complex. It can become difficult to debug what

is happening in stylesheet when the output is not what you expect. To
aid in debugging problems in XSL stylesheets, it is often helpful to
develop the stylesheet in small increments rather than creating the com-
plete stylesheet at one time. Write one rule at a time and run your trans-
formation, verifying that the node list returned is what you expect.
When you do encounter output that is not what you expect, you can be
relatively sure the problem lies in the last rule you added. This can save
you valuable time.
Debugging…
490 Chapter 9 • Working with XML
Summary
XML has emerged as the Web standard for representing and transmitting data
over the Internet.The W3C has worked to establish standards for XML and
related technologies including XML DOM, XPath, XSL, and XML schemas.
XML DOM is an API that is used to create, modify, and traverse XML docu-
ments. XPath is a language that is used to query XML documents. XSL translates
XML documents from one format to another format. XML schemas define the
structure and data types of the nodes in an XML document.All of these tech-
nologies are industry standards backed by the W3C.
Microsoft has embraced XML and provides implementations in the .NET
Framework for many of the technologies standardized by the W3C.The XML
DOM API is fully supported in the .NET Framework by the XmlDocument class.
The XmlDocument class allows you to create XML documents from scratch, per-
sist them to a number of different data stores and read them back into memory
from those data stores. Once in memory, an XML document can be traversed and
modified including adding, updating, and deleting nodes in the document.
In conjunction with ADO.NET and the XML support in the .NET
Framework, the ability to work with data as XML or as relational data is available
using C#.The XmlDataDocument class is used to read data into a DataSet class
object from an XML disk file or from a database. Once the XmlDataDocument is

created, the data is available for access relationally as table and columns or as
XML through the DOM API. XML schema support is provided by the .NET
Framework to specify the structure and data types of the data in XML docu-
ments including the XmlDataDocument class.The relationship between the
ADO.NET DataSet class and the XML API provides a powerful foundation to
develop end-to-end applications storing data in databases on both ends of a busi-
ness process and using XML to transmit the data between.
The .NET Framework supports XPath queries against XML DOM docu-
ments or the highly optimized XPathDocument class.The XPathNavigator class
works in conjunction with the XPathDocument to issue XPath queries against
XML documents in read-only mode. XPath queries can also be issued against the
XmlDocument class providing a convenient method to locate a specific node in a
document and then modify it. XPath queries are also instrumental in XSL trans-
formations.The .NET Framework fully supports XSL transformations as imple-
mented in the XslTransform class. XML-to-XML transformations as well as XML
to other formats are implemented with a minimum of source code.
www.syngress.com
Working with XML • Chapter 9 491
Use of XML is found throughout the .NET Framework and is instrumental
in the implementation of Web Services, as you will find out in Chapter 11.
Because XML is critical to .NET, developers benefit by first class, standards-based
support for XML in the .NET Framework.This chapter provided you with the
information you need to start taking advantages of that support in your own
XML-based applications.
Solutions Fast Track
Introduction to XML
; XML has emerged as the Web standard for representing and transmitting
data over the Internet.
; The W3C has standardized XML and related technologies including
XML DOM, XPath, XSL, and XML Schemas.

; The .NET Framework provides first class support for W3C-backed
XML standards.
; XML is prevalent throughout the .NET Framework including use in
configuration files, C# source code comments, and Web Services.
Working with XML DOM
; An XML document can be represented as a tree of nodes in memory,
which can be traversed and modified using an implementation of the
XML DOM API.
; The XmlDocument class is the .NET implementation of XML DOM.
; The XmlDocument class provides the ability to create an XML document,
add elements and attributes to a document, update nodes in the
document, delete nodes from the document, save the document to
persistent storage, and load the document into memory from persistent
storage.
www.syngress.com
492 Chapter 9 • Working with XML
Working with XML and Relational Data
; The DataSet class is an in-memory representation of relational data using
tables, columns, and rows.
; The XmlDataDocument class has a DataSet object as a member variable.
XML documents can be read into an XmlDataDocument object instance
and can then be manipulated using XML DOM method calls or by
relational method calls against the DataSet member variable.
; In conjunction with ADO.NET, the XML support in the .NET
Framework can be used to build powerful applications that access data as
XML or relational database data when appropriate.The conversion
between the two types of data is trivial to implement.
Working with XPath and XSL Transformations
; XPath support is built into the .NET Framework for use as a general-
purpose query tool or as part of XSL stylesheets.

; XPath queries can be performed against the read-only XPathDocument
class using the XPathNavigator class.The XmlDocument class can also be
queried using XPath to locate a node in a document, which can then be
modified if desired.
; XSL Transformations are implemented using the XslTransform class of the
.NET Framework allowing transformation of XML documents to other
formats including XML and HTML.
www.syngress.com
Working with XML • Chapter 9 493
Q: What W3C level of support is provided in the XML classes supplied with the
.NET Framework?
A: The XmlDataDocument class supports W3C DOM Core Level 1 and Core
Level 2 specifications.The XmlSchema class supports W3C XML Schemas for
Structures and the XML Schemas for Data Types specifications.The
XslTransform class supports the XSLT 1.0 specification. See the W3C Web site
for details on the specifications at: www.w3c.org.
Q: Which set of XML classes should I use to implement my project?
A: That depends on your needs and can be difficult to say. Here though are
some rules of thumb. If you need fast-forward, read-only access to the data,
use one of the XmlReader-derived classes, such as XmlTextReader. If you need
to do extensive updates to the document, use the XmlDocument class. If you
want fast query capabilities, use the XPathDocument class. If you want to read
and write from a database and then manipulate the results as XML, use the
XmlDataDocument class.
Q: I have two tables in a DataSet and have added a DataRelation, which estab-
lishes a parent-child relationship.When I write the XML file to disk, the
parent-child relationship isn’t represented.What is wrong?
A: Most likely you did not set the Nested property of the DataRelation to true. If
it is false, the elements associated with the child in the relationship will all
appear after the parent elements in the XML file.

www.syngress.com
Frequently Asked Questions
The following Frequently Asked Questions, answered by the authors of this book,
are designed to both measure your understanding of the concepts presented in
this chapter and to assist you with real-life implementation of these concepts. To
have your questions about this chapter answered by the author, browse to
www.syngress.com/solutions and click on the “Ask the Author” form.
494 Chapter 9 • Working with XML
Q: How do I create an XmlDocument instance from a string?
A: Here are two methods. One method is to use this:
doc.Load( new XmlTextReader( new StringReader( myString ) ) )
Another is to write this:
doc.InnerXml = myString
www.syngress.com

×