O'Reilly logo

C# in a Nutshell by Peter Drayton, Ted Neward, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Transforming a Document Using XSLT

A frequent usage of XPath is to find nodes for extraction and possible transformation into other XML documents, or into non-XML data, such as HTML or flat-file format for legacy consumption. While XPath provides a powerful API for selecting nodes from within an Infoset, writing the procedural code to execute query after query, along with the code to execute against each query result, is tedious and error-prone. Again, the W3C has anticipated this need and provided another XML-based standard, the XSL: Transformations specification (in which XSL originally stood for “eXtensible Stylesheet Language:”), for doing precisely this.

In the following example, we continue to use this XML book as our source data:

<book>
  <title>C# in a Nutshell</title>
  <authors>
    <author>Drayton</author>
    <author>Neward</author>
    <author>Albahari</author>
  </authors>
</book>

Suppose you wish to transform this source XML into a format more suitable for end-user consumption, such as HTML. For purely pedagogical reasons, we wish the title to display in bold font in an H1-style heading, with the authors’ names displayed in order in italic text.

Certainly, you could write the necessary C# code to execute two XPath queries, one to retrieve the title of the book (/book/title/text()) and another to retrieve the list of authors for the book (/book/authors/author/text()). You could then take each resulting XmlNodeList, walk through the results, and echo the HTML back to the caller. However, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required