use variable in xslt

Variables

we can define global variable at the beginning:


<xsl:variable name="reviewTypeVar" select="/submission/submissionModel/dataValue[@fieldName = 'reviewPrograms']/@value"/>
 <xsl:variable name="reviewTimeVar" select="/submission/submissionMetadata/@submitedOn"/>

TO use the variable just use: $


	<!-- Root level template -->
	<xsl:template match="submissionModel">
		<appendAndReplaceCommand>
			<xsl:if test="not(./dataValueGrid[@name=reviewHistoryList])">
				<dataValueGridAppendAndReplace name="reviewHistoryList">
					<row number="0">
						<dataValueAppendAndReplace fieldName="reviewRequestedDate">
							<xsl:value-of select="$reviewTimeVar" />
						</dataValueAppendAndReplace>
						<dataValueAppendAndReplace fieldName="reviewType">
							<xsl:value-of select="$reviewTypeVar" />
						</dataValueAppendAndReplace>
					</row>
				</dataValueGridAppendAndReplace>
			</xsl:if>
			<xsl:apply-templates />
		</appendAndReplaceCommand>
	</xsl:template>

not AND concat

use not() in the xls:if for negative:
<xsl:if test=”not(./dataValueGrid[@name=reviewHistoryList])”>….</xls:if>

use concat() for string concat, use “,” to seperate:
<xsl:value-of select=”concat(‘/Application/DirectFormAccess.jsp?requestInstance=’, $reviewInstanceIdVar)” />

xslt apply templates

When you use <xsl:apply-templates/>, it is really short for <xsl:apply-templates select="node()"/> and is being invoked inside of a template match on /, which is the root node of the document and an abstract concept for the top of the file. It’s children include the document element (i.e. <Page>), as well as any top-level comments or processing instructions that may be siblings of the document element.

<xsl:apply-templates> takes a sequence of nodes and goes through them one by one. For each, it locates the template with the highest priority that matches the node, and invokes it. So <xsl:apply-templates> is like a <xsl:for-each> with an <xsl:choose> inside, but more modular.

In contrast, <xsl:call-template> invokes a template by name. There’s no change to the context node (no <xsl:for-each>) and no choice about which template to use.

Templates are applied according to its priority, which range from -0.5 to 0.5.

Templates with more specific xpath expression has high priority.

  • Anything that’s repeated should be in a template (obviously)
  • Path matching should be matchable by a string search. apply-templates and template match should at least look similar. This becomes essential the larger your template becomes.
An XML document

<?xml version="1.0"?>
<db:article xmlns:db="http://ananas.org/2002/docbook/subset">
<db:title>XSLT, JSP and PHP</db:title>
<db:section>
<db:title>Is there a difference?</db:title>
<db:para>Yes there is! XSLT is a pure XML technology that
traces its roots to <db:emphasis>tree manipulation
algorithms</db:emphasis>. JSP and PHP offer an ingenious
solution to combine scripting languages with HTML/XML
tagging.</db:para>
<db:para>The difference may not be obvious when you're first
learning XSLT (after all, it offers tags and instructions),
but understanding the difference will make you a
<db:emphasis role="bold">stronger and better</db:emphasis>
developer.</db:para>
</db:section>
<db:section>
<db:title>How do I learn the difference?</db:title>
<db:para>Interestingly enough, you can code the XSLT algorithm
in XSLT... one cool way to experiment with the
difference.</db:para>
</db:section>
</db:article>

A simple stylesheet for HTML publishing

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:db="http://ananas.org/2002/docbook/subset">

<xsl:output method="html"/>

<xsl:template match="db:article">
   <html>
      <head><title>
          <xsl:value-of select="db:articleinfo/db:title"/>
      </title></head>
      <body>
         <xsl:apply-templates/>
      </body>
   </html>
</xsl:template>

<xsl:template match="db:para">
   <p><xsl:apply-templates/></p>
</xsl:template>

<xsl:template match="db:ulink">
   <a href="{@url}"><xsl:apply-templates/></a>
</xsl:template>

<xsl:template match="db:article/db:title">
   <h1><xsl:apply-templates/></h1>
</xsl:template>

<xsl:template match="db:title">
   <h2><xsl:apply-templates/></h2>
</xsl:template>

<xsl:template match="db:emphasis[@role='bold']">
   <b><xsl:apply-templates/></b>
</xsl:template>

<xsl:template match="db:emphasis">
   <i><xsl:apply-templates/></i>
</xsl:template>

</xsl:stylesheet>

XPath Basic Syntax

XPath uses path expressions to select nodes or node-sets in an XML document. The node is selected by following a path or steps.


The XML Example Document

We will use the following XML document in the examples below.

<?xml version=”1.0″ encoding=”ISO-8859-1″?>

<bookstore>

<book>
<title lang=”eng”>Harry Potter</title>
<price>29.99</price>
</book>

<book>
<title lang=”eng”>Learning XML</title>
<price>39.95</price>
</book>

</bookstore>

 


Selecting Nodes

XPath uses path expressions to select nodes in an XML document. The node is selected by following a path or steps. The most useful path expressions are listed below:

Expression Description
nodename Selects all nodes with the name “nodename
/ Selects from the root node
// Selects nodes in the document from the current node that match the selection no matter where they are
. Selects the current node
.. Selects the parent of the current node
@ Selects attributes

In the table below we have listed some path expressions and the result of the expressions:

Path Expression Result
bookstore Selects all nodes with the name “bookstore”
/bookstore Selects the root element bookstoreNote: If the path starts with a slash ( / ) it always represents an absolute path to an element!
bookstore/book Selects all book elements that are children of bookstore
//book Selects all book elements no matter where they are in the document
bookstore//book Selects all book elements that are descendant of the bookstore element, no matter where they are under the bookstore element
//@lang Selects all attributes that are named lang

 


Predicates

Predicates are used to find a specific node or a node that contains a specific value.

Predicates are always embedded in square brackets.

In the table below we have listed some path expressions with predicates and the result of the expressions:

Path Expression Result
/bookstore/book[1] Selects the first book element that is the child of the bookstore element.Note: IE5 and later has implemented that [0] should be the first node, but according to the W3C standard it should have been [1]!!
/bookstore/book[last()] Selects the last book element that is the child of the bookstore element
/bookstore/book[last()-1] Selects the last but one book element that is the child of the bookstore element
/bookstore/book[position()<3] Selects the first two book elements that are children of the bookstore element
//title[@lang] Selects all the title elements that have an attribute named lang
//title[@lang=’eng’] Selects all the title elements that have an attribute named lang with a value of ‘eng’
/bookstore/book[price>35.00] Selects all the book elements of the bookstore element that have a price element with a value greater than 35.00
/bookstore/book[price>35.00]/title Selects all the title elements of the book elements of the bookstore element that have a price element with a value greater than 35.00

 


Selecting Unknown Nodes

XPath wildcards can be used to select unknown XML elements.

Wildcard Description
* Matches any element node
@* Matches any attribute node
node() Matches any node of any kind

In the table below we have listed some path expressions and the result of the expressions:

Path Expression Result
/bookstore/* Selects all the child nodes of the bookstore element
//* Selects all elements in the document
//title[@*] Selects all title elements which have any attribute

 


Selecting Several Paths

By using the | operator in an XPath expression you can select several paths.

In the table below we have listed some path expressions and the result of the expressions:

Path Expression Result
//book/title | //book/price Selects all the title AND price elements of all book elements
//title | //price Selects all the title AND price elements in the document
/bookstore/book/title | //price Selects all the title elements of the book element of the bookstore element AND all the price elements in the document

 

 

FROM HERE

add CDATA to xml DOM tree

A CDATA section indicates a block that shouldn’t be parsed. To build a CDATA section just wrap the string with a CDATA object.

import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
  public static void main(String[] argv) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);

    factory.setExpandEntityReferences(false);

    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Element element = doc.getElementById("key1");

    // Add a CDATA section to the root element
    element = doc.getDocumentElement();
    CDATASection cdata = doc.createCDATASection("data");
    element.appendChild(cdata);

  }
}

If append TextNode directly, it will not appear as CDATA but just plain text.

xml parse line break, line feed lost

\n or line break or line feed in a string would be stripped by xml parser and replaced by space.

According to XML specification, any white space will be normalized into #xA;

In order to preserve the line feed, we can just replace all the \n with which is the legal line feed in XML. So when we later retrieve the String data from DOM, it will put \n back.

Notepad++ format xml file (indent)

TextFX

To Indent a XML file in notepad++, TextFX > TextFX HTML Tidy > Tidy Reindent XML

If the TextFX menu does not exist, you need to download & install the plugin. Plugins->Plugin Manager->Show Plugin Manager and then check the plugin TextFX Characters. Click ‘install,’ restart Notepad++.

libTidy.dll might not be included in the new version of NPP.

Solution is to download the 5.9 zip, then
copy one of the following folders:
ansi\plugins\Config\tidy or Unicode\plugins\Config\tidy
to your current Notepad++\plugins\Config folder

 

XML tools

Install the xml tools plugin would be a easier way to format xml. Using Pretty print under Plugins -> xml tools