Friday, November 27, 2009

XSLT handbook / Cheat-sheet

Howdy,

This time I came up with an XSLT handbook. Being a developer if you ever come cross to XSLT development this blog can help you. As over here I have added all most all kwon topics using which you can start programming in XSLT. Though I have in brief about each topic to know in detail you can click on name of the topic an you will be redirect to the w3school site which i have used to write this blog. hope you all will enjoy this handbook while working with XSLT :)


1) Xsl:stylesheet/xsl:transform - The root element that declares the document to be an XSL style sheet is <xsl:stylesheet> or <xsl:transform>. <xsl:stylesheet> and <xsl:transform> are completely synonymous and either can be used!

2) Href - To provide link or reference syntax would be <?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>

3) Xsl:template - An XSL style sheet consists of one or more set of rules that are called templates. A template contains rules to apply when a specified node is matched. <xsl:template match="/">

4) Xsl:value-of - The <xsl:value-of> element is used to extract the value of a selected node. Example - <td><xsl:value-of select="catalog/cd/title" /></td>

5) Xsl:for-each - The <xsl:for-each> element allows you to do looping in XSLT. Legal filter operators are: = (equal), != (not equal), < less than, > greater than. Example - <xsl:for-each select="catalog/cd"> <p><xsl:value-of select="title" /></p> </xsl:for-each>

6) xsl:sort - The <xsl:sort> element is used to sort the output. Example - <xsl:sort select="artist"/>

7) Xsl:if - The <xsl:if> element is used to put a conditional test against the content of the XML file. Example - <xsl:if test="price > 10"> logic.. </xsl:if>

8) Xsl:choose - The <xsl:choose> element is used in conjunction with <xsl:when> and <xsl:otherwise> to express multiple conditional tests <xsl:choose> <xsl:when test="price > 10"> some logic.. </xsl:when> <xsl:when test="price > 9"> some logic </xsl:when> <xsl:otherwise> default logic </xsl:otherwise> </xsl:choose>

9) Xsl:apply-templates - The <xsl:apply-templates> element applies a template to the current element or to the current element's child nodes. If we add a select attribute to the <xsl:apply-templates> element it will process only the child element that matches the value of the attribute. We can use the select attribute to specify in which order the child nodes are to be processed. Syntax - <xsl:apply-templates select="expression" mode="name">

10) xsl:variable - The <xsl:variable> element is used to declare a local or global variable. Syntax - <xsl:variable name="name" select="expression">

11) xsl:call-template - The <xsl:call-template> element calls a named template. Syntax - <xsl:call-template name="templatename">

12) xsl:attribute - The <xsl:attribute> element is used to add attributes to elements. Note that the <xsl:attribute> element replaces existing attributes with equivalent names. Example - <a><xsl:attribute name="href"><xsl:value-of select="RSSLinks/FeedLink"/></xsl:attribute> <img src="images/rss_xml.gif" border="0"/></a>

13) xsl:import - The <xsl:import> element is a top-level element that is used to import the contents of one style sheet into another. An imported style sheet has lower precedence than the importing style sheet. Note that this element must appear as the first child node of <xsl:stylesheet> or <xsl:transform>. syntax - <xsl:import href="URI"/>

14) xsl:apply-imports - The <xsl:apply-imports> element applies a template rule from an imported style sheet. Template rules in imported style sheets have lower precedence than template rules in main style sheets. The <xsl:apply-imports> is used when we want to use a template rule from the imported style sheet rather than an equivalent rule in the main style sheet. Syntax - <xsl:apply-imports/>

15) xsl:attribute-set - The <xsl:attribute-set> element creates a named set of attributes. The attribute-set can be applied as whole to the output document. Note that it Must be child of <xsl:stylesheet> or <xsl:transform>. Example - <xsl:attribute-set name="font"><xsl:attribute name="fname">Arial</xsl:attribute> <xsl:attribute name="size">14px</xsl:attribute><xsl:attribute name="color">red</xsl:attribute> </xsl:attribute-set>

16) xsl:comment - The <xsl:comment> element is used to create a comment node in the result tree. Syntax - <xsl:comment>This is a comment!</xsl:comment>

17) xsl:copy - The <xsl:copy> element creates a copy of the current node. Note that Namespace nodes of the current node are automatically copied as well, but child nodes and attributes of the current node are not automatically copied!

18) xsl:copy-of - The <xsl:copy-of> element creates a copy of the current node. Note that namespace nodes, child nodes, and attributes of the current node are automatically copied as well! This element can be used to insert multiple copies of the same node into different places in the output. Syntax - <xsl:copy-of select="expression"/>

19) xsl:element - The <xsl:element> element is used to create an element node in the output document. Example - <xsl:element name="singer"><xsl:value-of select="artist" /> </xsl:element>

20) xsl:include - The <xsl:include> element is a top-level element that includes the contents of one style sheet into another. An included style sheet has the same precedence as the including style sheet. Note that this element must appear as a child node of <xsl:stylesheet> or <xsl:transform>. Systax - <xsl:include href="URI"/>


21) xsl:key - The <xsl:key> element is a top-level element which declares a named key that can be used in the style sheet with the key() function. Syntax - <xsl:key name="name" match="pattern" use="expression"/>

22) xsl:message - The <xsl:message> element writes a message to the output. This element is primarily used to report errors. This element can contain almost any other XSL element (<xsl:text>, <xsl:value-of>, etc.). The terminate attribute gives you the choice to either quit or continue the processing when an error occurs. Example - <xsl:message terminate="yes"> Error: Artist is an empty string! </xsl:message>

23) xsl:namespace-alias - The <xsl:namespace-alias> element is used to replace a namespace in the style sheet to a different namespace in the output. Note that <xsl:namespace-alias> is a top-level element, and must be a child node of <xsl:stylesheet> or <xsl:transform>.

24) xsl:number - The <xsl:number> element is used to determine the integer position of the current node in the source. It is also used to format a number. Example - <xsl:number value="12" grouping-size="1" grouping-separator="#" format="I"/> Output: X#I#I

25) xsl:output - The <xsl:output> element defines the format of the output document. Note that <xsl:output> is a top-level element, and must appear as a child node of <xsl:stylesheet> or <xsl:transform>.

26) xsl:param - The <xsl:param> element is used to declare a local or global parameter. Note that the parameter is global if it's declared as a top-level element, and local if it's declared within a template. Syntax - <xsl:param name="name" select="expression">

27) xsl:strip-space and xsl:preserve-space - The <xsl:preserve-space> element is used to define the elements for which white space should be preserved. The <xsl:strip-space> element is used to define the elements for which white space should be removed. Note that the preserving white space is the default setting, so using the <xsl:preserve-space> element is only necessary if the <xsl:strip-space> element is used. Note that the <xsl:preserve-space> element and the <xsl:strip-space> element are top-level elements. Example - <xsl:strip-space elements="country company price year" /> <xsl:preserve-space elements="title artist" />

28) xsl:processing-instruction - The <xsl:processing-instruction> element writes a processing instruction to the output. Syntax - <xsl:processing-instruction name="process-name">

29) xsl:text - The <xsl:text> element is used to write literal text to the output. This element may contain literal text, entity references, and #PCDATA. Syntax - <xsl:text disable-output-escaping="yes|no">

30) xsl:with-param - The <xsl:with-param> element defines the value of a parameter to be passed into a template. Note that the value of the name attribute of <xsl:with-param> must match a name in an <xsl:param> element (the <xsl:with-param> element is ignored if there is no match). Also note that the <xsl:with-param> element is allowed within <xsl:apply-templates> and <xsl:call-template>. You can add a value to the parameter by the content of the <xsl:with-param> element OR by the select attribute! Syntax - <xsl:with-param name="name" select="expression">

31) xsl:decimal-format - The <xsl:decimal-format> element defines the characters and symbols to be used when converting numbers into strings, with the format-number() function. All countries do not use the same characters for separating the decimal part from the integer part, and for grouping digits. With the <xsl:decimal-format> element you can change special characters to other symbols. This element is a top level element. The format-number() function can refer to the <xsl:decimal-format> element by name. Example - <xsl:decimal-format name="euro" decimal-separator="," grouping-separator="."/>

32) xsl:fallback - The <xsl:fallback> element specifies an alternate code to run if the XSL processor does not support an XSL element. Syntax - <xsl:fallback> <!-- Content: template --> </xsl:fallback>

33) current() - The current() function returns a node-set that contains only the current node. Usually the current node and the context node are the same. <xsl:value-of select="current()"/> is equal to <xsl:value-of select="."/> However, there is one difference. Look at the following XPath expression: "catalog/cd". This expression selects the <catalog> child nodes of the current node, and then it selects the <cd> child nodes of the <catalog> nodes. This means that on each step of evaluation, the "." has a different meaning. The following line: <xsl:apply-templates select="//cd[@title=current()/@ref]"/> will process all cd elements that have a title attribute with value equal to the value of the current node's ref attribute. This is different from <xsl:apply-templates select="//cd[@title=./@ref]"/> that will process all cd elements that have a title attribute and a ref attribute with the same value.

34) document() - The document() function is used to access nodes in an external XML document. The external XML document must be valid and parsable. One way to use this function is to look up data in an external document. For example we want to find the Celsius value from a Fahrenheit value and we refer to a document that contains some pre-computed results: <xsl:value-of select="document('celsius.xml')/celsius/result[@value=$value]"/>

35) format-number() - The format-number() function is used to convert a number into a string. Syntax - string format-number(number,format,[decimalformat])

36) generate-id() - The generate-id() function returns a string value that uniquely identifies a specified node. If the node-set specified is empty, an empty string is returned. If you omit the node-set parameter, it defaults to the current node. Example - <a href="#{generate-id(artist)}">

37) key() - The key() function returns a node-set from the document, using the index specified by an <xsl:key> element.

Thursday, November 12, 2009

Creating and transforming XML using LINQ

XML has achieved tremendous adoption as a basis for formatting data whether in Word files, in configuration files, or in databases; XML seems to be everywhere. Yet, from a development perspective, XML is still hard to work with. If you ask the average software developer to work in XML you will likely hear a heavy sigh. The API choices for working with XML seem to be either aged and verbose such as DOM or XML specific such as XQuery or XSLT which require motivation, study, and time to master. LINQ to XML, a component of the LINQ project, aims to address this issue. LINQ to XML is a modernized in-memory XML programming API designed to take advantage of the latest .NET Framework language innovations. It provides both DOM and XQuery/XPath like functionality in a consistent programming experience across the different LINQ-enabled data access technologies.

In this article I will explore some of the features available in .NET Framework release 3.5 related to LINQ for XML. This is, of course, not an extensive discussion, merely a familiarization and stepping stone for more learning and exploration.

Let’s start with one of the old ways of creating the xml. Then later on I will explain how the same can be written using new LINQ to XML API.

Old WAY of doing things

public void CreateEmployeesOld()
{
XmlElement root = m_doc.CreateElement("employees");
root.AppendChild(AddEmployee(1, "John doe", DateTime.Parse("12/12/2005"), true));
root.AppendChild(AddEmployee(2, "Kim", DateTime.Parse("11/23/1999"), true));
root.AppendChild(AddEmployee(3, "Carla", DateTime.Parse("2/6/2008"), false));
root.AppendChild(AddEmployee(4, "Aleks", DateTime.Parse("10/6/1998"), false));
m_doc.AppendChild(root);
Response.Write(m_doc.OuterXml);
}

private static XmlElement AddEmployee(int ID, string name, DateTime hireDate, bool isSalaried)
{
XmlElement employee = m_doc.CreateElement("employee");
XmlElement nameElement = m_doc.CreateElement("name");
nameElement.InnerText = name;
XmlElement hireDateElement = m_doc.CreateElement("hire_date");
hireDateElement.InnerText = hireDate.ToShortDateString();
employee.SetAttribute("id", ID.ToString());
employee.SetAttribute("salaried", isSalaried.ToString());
employee.AppendChild(nameElement);
employee.AppendChild(hireDateElement);
return employee;
}

Now say for, once you have created the employee xml and now you want to transform it to new set of xml elements, then old way need help of XSLT. But in below example of LINQ to XML I have explained that too. How easy it would be to transform one xml to another one without using XSLT

New WAY of doing things

public void CreateEmployeesNew()
{
// creating employee xml
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("A sample xml file"),
new XElement("employees",
new XElement("employee",
new XAttribute("id", 1),
new XAttribute("salaried", "true"),
new XElement("name", "John doe"),
new XElement("hire_date", "12/12/2005")),
new XElement("employee",
new XAttribute("id", 2),
new XAttribute("salaried", "true"),
new XElement("name", "Kim"),
new XElement("hire_date", "11/23/1999")),
new XElement("employee",
new XAttribute("id", 3),
new XAttribute("salaried", "false"),
new XElement("name", "Carla"),
new XElement("hire_date", "2/6/2008")),
new XElement("employee",
new XAttribute("id", 4),
new XAttribute("salaried", "false"),
new XElement("name", "Aleks"),
new XElement("hire_date", "10/6/1998"))
)
);
Response.Write("
" + doc + "
");

// transforming employee xml in to newer xml format.
XElement element = new XElement("salaried_employees", from e in doc.Descendants("employee")
where e.Attribute("salaried").Value == "true"
select new XElement("employee",
new XElement(e.Element("name"))));
Response.Write("
" + element + "
");
}

To conclude this I would say, XML is fantastic construct that has been deeply ingrained into just about everything. Having the ability to easily construct, query, transform and manipulate XML documents is an invaluable service that will improve the speed of which applications can be built and the quality of those applications.This article is not an exhaustive investigation of LINQ to XML; there have been many other articles, snippets and blogs written on the subject. It mainly just a taste and familiarization of what is possible using .NET 3.5.