Home > SKIP > XML and AJAX > XML & XSL

XML and XSL

What is XML?

XML (eXtensible markup language) is all about describing data.
<?xml version=“1.0” encoding=“ISO-8859-1”?>
<products>

<productname>Shoes</productname>
<qty>12</qty>
<totalcost>100</totalcost>
<discount>10</discount>

</products>

An XML tag is not something predefined but it is something you have to define according to your needs. For instance in the above example of <products> all tags are defined according to business needs.

The XML document is self explanatory, any one can easily understand looking at the XML data what exactly it means.

  • “Version” tag shows which version is XML is used.
  • What is ROOT element in XML?

In the above sample example <products></products> tag is the root element. Root element is the top most element for a XML.

  • All the tags should have the closing tag otherwise it will not work.
  • XML is case sensitive.

What is the difference between XML and HTML?
XML describes the data and HTML describes how the data should be displayed.

Is XML meant to replace HTML?
No, they both go together XML for describe DATA and HTML for displaying data.

Why we are using XML files in our applications?
XML files is use for exchanging a data and any two different application can read the data from the xml file.

DTD(Document Type Definition) it is used to defines how your XML should structure. DOM is a W3C recommended way for treating XML documents. In DOM we load entire XML document into memory and allows us to manipulate the structure and data of XML document.

CDATA section in XML is used for if you want to exclude some elements you will need to put those elements in CDATA.

<product itemnumber=“d123” > </product>
In above example product is an element and itemnumber is an attribute.

XML Parser

XML parser sits in between the XML document and the application who want to use the XML document. Parser exposes set of well defined interfaces which can be used by the application for adding, modifying and deleting the XML document contents. Now whatever interfaces XML parser exposes should be standard or else that would lead to different vendors preparing there own custom way of interacting with XML document.

There are two standard specifications which are very common and should be followed by a XML parser.

  • DOM (Document Object Model)
  • SAX (Simple API for XML)

DOM Parser loading XML document

DOM Parser loading XML document

SAX (Simple API for XML)

  • SAX parser does not load the whole DOM in to memory but has event based approach.
  • It parsing the XML File emits events.
  • It only sends those events to the application which is register to the SAX parser.

XML in Dot Net (Using System.xml)

  • Provides standards-based support for processing XML
  • It Includes classes, Interfaces, Delegates, Enumerations

System.Xml Namespace -- Classes

Class Description
NameTable Implements a single-threaded XmlNameTable.
UniqueId A unique identifier optimized for Guids.
XmlAttribute Represents an attribute. Valid and default values for the attribute are defined in a document type definition (DTD) or schema.
XmlAttributeCollection Represents a collection of attributes that can be accessed by name or index. XmlAttributeCollection extends the XmlNamedNodeMap class adding strongly typed helper methods. You can use this class to add, remove or modify attributes in the collection. XmlAttributeCollection is returned by the XmlElement.Attributes property.
XmlBinaryReaderSession Enables optimized strings to be managed in a dynamic way.
XmlBinaryWriterSession Enables using a dynamic dictionary to compress common strings that appear in a message and maintain state.
XmlCDataSection Represents a CDATA section.
XmlCharacterData Provides text manipulation methods that are used by several classes.
XmlComment Represents the content of an XML comment.
XmlConvert Encodes and decodes XML names and provides methods for converting between common language runtime types and XML Schema definition language (XSD) types. When converting data types the values returned are locale independent.
XmlDataDocument Allows structured data to be stored, retrieved, and manipulated through a relational DataSet.
XmlDeclaration Represents the XML declaration node <?xml version='1.0'...?>.
XmlDictionary Implements a dictionary used to optimize Windows Communication Foundation (WCF)'s XML reader/writer implementations.
XmlDictionaryReader An abstract class that the Windows Communication Foundation (WCF) derives from to do serialization and deserialization.

XmlException

Returns detailed information about the last exception.

XmlImplementation

Defines the context for a set of XmlDocument objects.

XmlLinkedNode

Gets the node immediately preceding or following this node.

XmlNamedNodeMap

Represents a collection of nodes that can be accessed by name or index.

XmlNamespaceManager

Resolves, adds, and removes namespaces to a collection and provides scope management for these namespaces.

XmlNameTable

Table of atomized string objects.

XmlNode

Represents a single node in the XML document.

XmlNodeChangedEventArgs

Provides data for the NodeChanged, NodeChanging, NodeInserted, NodeInserting, NodeRemoved and NodeRemoving events.

XmlNodeList

Represents an ordered collection of nodes.

XmlNodeReader

Represents a reader that provides fast, non-cached forward only access to XML data in an XmlNode.

XmlNotation

Represents a notation declaration, such as <!NOTATION... >.

XmlParserContext

Provides all the context information required by the XmlReader to parse an XML fragment.

XmlProcessingInstruction

Represents a processing instruction, which XML defines to keep processor-specific information in the text of the document.

XmlQualifiedName

Represents an XML qualified name.

XmlReader

Represents a reader that provides fast, non-cached, forward-only access to XML data.

XmlReaderSettings

Specifies a set of features to support on the XmlReader object created by the Create method.

XmlResolver

Resolves external XML resources named by a Uniform Resource Identifier (URI).

XmlTextWriter

Represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations.

XmlUrlResolver

Resolves external XML resources named by a Uniform Resource Identifier (URI).

XmlValidatingReader

Obsolete. Represents a reader that provides document type definition (DTD), XML-Data Reduced (XDR) schema, and XML Schema definition language (XSD) validation.

XmlWhitespace

Represents white space in element content.

XmlWriter

Represents a writer that provides a fast, non-cached, forward-only means of generating streams or files containing XML data.

XmlDocument

Represents an attribute. Valid and default values for the attribute are defined in a DTD or schema.
The XmlElement class has several methods which allow you to access attribute nodes (XmlElement.GetAttribute, XmlElement.SetAttribute, XmlElement.RemoveAttribute, and so on). Additionally, you can call the XmlElement.Attributes property which returns an XmlAttributeCollection enabling you to access attributes by name or index from the collection.

XmlDocumentFragment

Represents a lightweight object that is useful for tree insert operations.

XmlDocumentType

Represents the document type declaration.

XmlElement

Represents an element.

XmlEntity

Represents an entity declaration, such as <!ENTITY... >.

XmlEntityReference

Represents an entity reference node.

XmlDictionaryReaderQuotas

Contains configurable quota values for XmlDictionaryReaders.

XmlDictionaryString

Represents an entry stored in a XmlDictionary.

XmlDictionaryWriter

An abstract class that the Windows Communication Foundation (WCF) derives from to do serialization and deserialization.

XmlSecureResolver

Helps to secure another implementation of XmlResolver by wrapping the XmlResolver object and restricting the resources that the underlying XmlResolver has access to.

XmlSignificantWhitespace

Represents white space between markup in a mixed content node or white space within an xml:space= 'preserve' scope. This is also referred to as significant white space.

XmlText

Represents the text content of an element or attribute.

XmlTextReader

Represents a reader that provides fast, non-cached, forward-only access to XML data.

XmlWriterSettings

Specifies a set of features to support on the XmlWriter object created by the XmlWriter..::.Create method.

System.Xml Namespace -- Interface

Interface

Description

IFragmentCapableXmlDictionaryWriter

Contains properties and methods that when implemented by a XmlDictionaryWriter, allows processing of XML fragments.

IHasXmlNode

Enables a class to return an XmlNode from the current context or position.

IStreamProvider

An interface that can be implemented by classes providing streams.

IXmlBinaryReaderInitializer

Provides methods for reinitializing a binary reader to read a new document.

IXmlBinaryWriterInitializer

Specifies implementation requirements for XML binary writers that derive from this interface.

IXmlDictionary

An interface that defines the contract that an Xml dictionary must implement to be used by XmlDictionaryReader and XmlDictionaryWriter implementations.

IXmlLineInfo

Provides an interface to enable a class to return line and position information.

IXmlMtomReaderInitializer

Specifies implementation requirements for XML MTOM readers that derive from this interface.

IXmlMtomWriterInitializer

When implemented by an MTOM writer, this interface ensures initialization for an MTOM writer.

IXmlNamespaceResolver

Provides read-only access to a set of prefix and namespace mappings.

IXmlTextReaderInitializer

Specifies implementation requirements for XML text readers that derive from this interface.

IXmlTextWriterInitializer

Specifies implementation requirements for XML text writers that derive from this interface.

System.Xml Namespace -- Delegate

Delegate

Description

OnXmlDictionaryReaderClose

delegate for a callback method when closing the reader.

XmlNodeChangedEventHandler

Represents the method that handles

System.Xml Namespace -- Enumeration

Enumeration

Description

ConformanceLevel

Specifies the amount of input or output checking that the created XmlReader and XmlWriter objects perform.

EntityHandling

Specifies how the XmlTextReader or XmlValidatingReader handle entities.

Formatting

Specifies formatting options for the XmlTextWriter.

NewLineHandling

Specifies how to handle line breaks.

ReadState

Specifies the state of the reader.

ValidationType

Specifies the type of validation to perform.

WhitespaceHandling

Specifies how white space is handled.

WriteState

Specifies the state of the XmlWriter.

XmlDateTimeSerializationMode

Specifies how to treat the time value when converting between string and DateTime.

XmlNamespaceScope

Defines the namespace scope.

XmlNodeChangedAction

Specifies the type of node change.

XmlNodeOrder

Describes the document order of a node compared to a second node.

XmlNodeType

Specifies the type of node.

XmlOutputMethod

Specifies the method used to serialize the XmlWriter output.

XmlSpace

Specifies the current xml:space scope.

XmlTokenizedType

Represents the XML type for the string. This allows the string to be read as a particular XML type, for example a CDATA section type.

XPath in Dot Net (Using System.Xml.XPath )

System.Xml.XPath Namespace
System.Xml.XPath namespace contains the interfaces, enumerations, classes that defines a cursor model for navigating and editing XML information.

Classes

  • XPathDocument
  • XPathException
  • XPathExpression
  • XPathItem
  • XPathNavigator
  • XPathNodeIterator

Interfaces

  • IXPathNavigable

Enumerations

  • XmlCaseOrder
  • XmlDataType
  • XmlSortOrder
  • XPathNamespaceScope
  • XPathNodeType
  • XPathResultType

System.Xml.XPath Namespace -- Classes

Class

Description

Declaration

XPathDocument

Provides a fast, read-only, in-memory representation of an XML document using the XPath data model.

Dim instance As XPathDocument

XPathException

Provides the exception thrown when an error occurs while processing an XPath expression.

Dim instance As XPathException

XPathExpression

Provides a typed class that represents a compiled XPath expression.

Dim instance As XPathExpression

XPathItem

Represents an item in the XQuery 1.0 and XPath 2.0 Data Model.

Dim instance As XPathItem

XPathNavigator

Provides a cursor model for navigating and editing XML data.

Dim instance As XPathNavigator

XPathNodeIterator

Provides an iterator over a selected set of nodes.

Dim instance As XPathNodeIterator

System.Xml.XPath Namespace -- Interface

Interface

Description

Declaration

IXPathNavigable

Provides an accessor to the XPathNavigator class.

Dim instance As IXPathNavigable

System.Xml.XPath Namespace -- Enumeration

Enumeration

Description

Declaration

XmlCaseOrder

Specifies the sort order for uppercase and lowercase letters.

Dim Instance As XmlCaseOrder

XmlDataType

Specifies the data type used to determine sort order.

Dim Instance As XmlDataType

XmlSortOrder

Specifies the sort order.

Dim Instance As XmlSortOrder

XPathNamespaceScope

Defines the namespace scope.

Dim Instance As XPathNamespaceScope

XPathNodeType

Defines the XPath node types that can be returned from the XPathNavigator class.

Dim Instance As XPathNodeType

XPathResultType

Specifies the return type of the XPath expression.

Dim Instance As XPathResultType

What is XSL?

XSL (the eXtensible Stylesheet Language) is used to transform XML document to some other document. It transform the document which can convert XML to some other document. If we apply XSL to XML it convert it to HTML document output.

HTML pages uses predefined tags, and the meaning of these tags is well understood: <p> means a paragraph and <h1> means a header, and the browser knows how to display these pages.

With XML we can use any tags we want, and the meaning of these tags are not automatically understood by the browser: <table> could mean a HTML table or maybe a piece of furniture. Because of the nature of XML, there is no standard way to display an XML document.

In order to display XML documents, it is necessary to have a mechanism to describe how the document should be displayed. One of these mechanisms is Cascading Style Sheets (CSS), but XSL (eXtensible Stylesheet Language) is the preferred style sheet language of XML, and XSL is far more sophisticated than the CSS  used by HTML.

XSL Architecture

XSL Architecture

The World Wide Web Consortium (W3C) issued the XSL transformations, or XSLT for short, as a recommendation - a type of W3C standard. The purpose of this language, written in XML, is to allow webmasters and programmers to take XML data with any desired structure and use them to generate something which the server can supply to the user as an HTML page.

The processing of XML sources via an XSLT program basically means that the latter uses the source to generate a document tree and converts this to a result tree by executing the instructions specified in the stylesheet.

XSL consists of two parts:

  • A method for transforming XML documents
  • A method for formatting XML documents

XSL as a language that can transform XML into HTML, a language that can filter and sort XML data and a language that can format XML data, based on the data value, like displaying negative numbers in red.

XSL can be used to define how an XML file should be displayed by transforming the XML file into a format that is recognizable to a browser. One such format is HTML. Normally XSL does this by transforming each XML element into an HTML element.

XSL can also add completely new elements into the output file, or remove elements. It can rearrange and sort the elements, test and make decisions about which elements to display.

Transforming XML to HTML

XML File sample.xml
<?xml version="1.0" encoding="ISO8859-1" ?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST> <COUNTRY>USA</COUNTRY> <COMPANY>Columbia</COMPANY> <PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
</CATALOG>

XSL File sample.xsl
<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<html>
<body>
<table border="2" bgcolor="yellow">
<tr> <th>Title</th> <th>Artist</th> </tr>
<xsl:for-each select="CATALOG/CD">
<tr>
<td><xsl:value-of select="TITLE"/></td>
<td><xsl:value-of select="ARTIST"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

In the above file, the xsl:for-each element locates elements in the XML document and repeats a template for each one. The select attribute describes the element in the source document. The syntax for this attribute is called an XSL Pattern, and works like navigating a file system where a forward slash (/) selects subdirectories. The xsl:value-of element selects a child in the hierarchy and inserts the content of that child into the template.

Since an XSL style sheet is an XML file itself, the file begins with an xml declaration. The xsl:stylesheet element indicates that this document is a style sheet. The template has also been wrapped with xsl:template match="/" to indicate that this is a template that corresponds to the root (/) of the XML source document.

XSL - On the Client

HTML File sample.html
<html>
<body>
<script language="javascript">
// Load XML
var xml = new ActiveXObject("Microsoft.XMLDOM")
xml.async = false xml.load(“sample.xml")
// Load the XSL
var xsl = new ActiveXObject("Microsoft.XMLDOM")
xsl.async = false xsl.load("sample.xsl")
// Transform
document.write(xml.transformNode(xsl))
</script>
</body>
</html>

The first block of code creates an instance of the Microsoft XML parser (XMLDOM), and loads the XML document into memory. The second block of code creates another instance of the parser and loads the XSL document into memory. The last line of code transforms the XML document using the XSL document, and writes the result to the HTML document.

XSL - Sort

<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<html>
<body>
<table border="2" bgcolor="yellow">
<tr> <th>Title</th> <th>Artist</th></tr>
<xsl:for-each select="CATALOG/CD" order-by="+ ARTIST">
<tr>
<td><xsl:value-of select="TITLE"/></td>
<td><xsl:value-of select="ARTIST"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

To output this XML file as an ordinary HTML file, and sort it at the same time, simply add an order-by attribute to your for-each element like this:

<xsl:for-each select="CATALOG/CD" order-by="+ ARTIST">
The order-by attributes takes a plus (+) or minus (-) sign, to define an ascending or descending sort order, and an element name to define the sort element.

<html>
<body>
<script language="javascript">
// Load XML
var xml = new ActiveXObject("Microsoft.XMLDOM")
xml.async = false xml.load(“sample.xml")
// Load the XSL
var xsl = new ActiveXObject("Microsoft.XMLDOM")
xsl.async = false xsl.load(“sample.xsl")
// Transform
document.write(xml.transformNode(xsl))
</script>
</body>
</html>

XSL - Filter Query

Legal filter operators are:
=  (equal)
=! (not equal)
&LT& less than
&GT& greater than

<xsl:for-each select="CATALOG/CD[ARTIST='Bob Dylan']"> <tr> <td><xsl:value-of select="TITLE"/></td> <td><xsl:value-of select="ARTIST"/></td> </tr> </xsl:for-each>

XSL - Conditional If

<xsl:for-each select="CATALOG/CD">
<xsl:if match=".[ARTIST='Bob Dylan']">
<tr>
<td><xsl:value-of select="TITLE"/></td> <td><xsl:value-of select="ARTIST"/></td>
</tr>
</xsl:if>
</xsl:for-each>

To put an conditional if test against the content of the file, simply add an xsl:if element to your XSL document like this:
<xsl:if match=".[ARTIST='Bob Dylan']"> ... some output ... </xsl:if>

XSL - Conditional Choose

<xsl:for-each select="CATALOG/CD">
<tr>
<td><xsl:value-of select="TITLE"/></td>
<xsl:choose>
<xsl:when match=".[ARTIST='Bob Dylan']">
<td bgcolor="#ff0000">
<xsl:value-of select="ARTIST"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="ARTIST"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>

To insert an conditional choose test against the content of the file, simply add an xsl:choose, xsl:when and xsl:otherwise elements to your XSL document like this:
<xsl:choose>    <xsl:when match=".[ARTIST='Bob Dylan']">       ... some code ...    </xsl:when>    <xsl:otherwise>       ... some code ....    </xsl:otherwise> </xsl:choose>

Transforming it on the Client

<html>
<body>
<script language="javascript">
// Load XML
var xml = new ActiveXObject("Microsoft.XMLDOM")
xml.async = false xml.load("cd_catalog.xml")
// Load the XSL
var xsl = new ActiveXObject("Microsoft.XMLDOM")
xsl.async = false xsl.load("cd_catalog_filter.xsl")
// Transform
document.write(xml.transformNode(xsl))
</script>
</body>
</html>

XSL in Dot Net (Using System.xml.Xsl)

  • The System.Xml.Xsl namespace provides support for Extensible Stylesheet Transformation (XSLT) transforms.
  • It Includes classes, Interfaces, Delegates

System.Xml.Xsl Namespace -- Classes

Class

Description

Declaration

XslCompiledTransform

Transforms XML data using an XSLT style sheet.

Dim instance As XslCompiledTransform

Methods

Equals

Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)

GetHashCode

Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

GetType

Gets the Type of the current instance. (Inherited from Object.)

Load

Overloaded. Compiles the style sheet. 

ReferenceEquals

Determines whether the specified Object instances are the same instance. (Inherited from Object.)

ToString

Returns a String that represents the current Object. (Inherited from Object.)

Transform

Overloaded. Executes the XSLT transformation.

Properties

OutputSettings

Gets an XmlWriterSettings object that contains the output information derived from the xsl:output element of the style sheet.

TemporaryFiles

Gets the TempFileCollection that contains the temporary files generated on disk after a successful call to the Load method.

Protected Methods

Finalize

Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)

MemberwiseClone

Creates a shallow copy of the current Object. (Inherited from Object.)

Class

Description

Declaration

XslCompiledTransform

Transforms XML data using an XSLT style sheet.

Dim instance As XslCompiledTransform

Methods

Equals

Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)

GetHashCode

Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

GetType

Gets the Type of the current instance. (Inherited from Object.)

Load

Overloaded. Compiles the style sheet. 

ReferenceEquals

Determines whether the specified Object instances are the same instance. (Inherited from Object.)

ToString

Returns a String that represents the current Object. (Inherited from Object.)

Transform

Overloaded. Executes the XSLT transformation.

Properties

OutputSettings

Gets an XmlWriterSettings object that contains the output information derived from the xsl:output element of the style sheet.

TemporaryFiles

Gets the TempFileCollection that contains the temporary files generated on disk after a successful call to the Load method.

Protected Methods

Finalize

Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)

MemberwiseClone

Creates a shallow copy of the current Object. (Inherited from Object.)

Protected Methods

Finalize

Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)

MemberwiseClone

Creates a shallow copy of the current Object. (Inherited from Object.)

Public Events

XsltMessageEncountered

Occurs when a message is specified in the style sheet by the xsl:message element. 

XsltCompileException

The exception that is thrown by the Load method when an error is found in the XSLT style sheet.

 

Public Properties

Data

Gets a collection of key/value pairs that provide additional, user-defined information about the exception.(Inherited from Exception.)

HelpLink

Gets or sets a link to the help file associated with this exception.(Inherited from Exception.)

InnerException

Gets the Exception instance that caused the current exception.(Inherited from Exception.)

LineNumber

Gets the line number indicating where the error occurred in the style sheet.(Inherited from XsltException.)

LinePosition

Gets the line position indicating where the error occurred in the style sheet.(Inherited from XsltException.)

Message

Gets the formatted error message describing the current exception.(Inherited from XsltException.)

Source

Gets or sets the name of the application or the object that causes the error.(Inherited from Exception.)

SourceUri

Gets the location path of the style sheet.(Inherited from XsltException.)

StackTrace

Gets a string representation of the frames on the call stack at the time the current exception was thrown.(Inherited from Exception.)

TargetSite

Gets the method that throws the current exception.(Inherited from Exception.)

HResult

Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.(Inherited from Exception.)