Study xsl with me (ii)

Source: Internet
Author: User
Tags end eval expression functions numeric value object model string tag name
Table I, operators and special character operators describe/select child elements, returns the immediate child element of the left element; if "/" is at the left, the direct child element//recursive descent that selects the root node, regardless of depth, searches for the specified element; If the leftmost representation indicates a recursive descent from the root node. Search for the specified element .Represents the current element * wildcard character, selecting any element, regardless of the name @

Gets the property value as a prefix to the property name

@*

wildcard character, select any property, regardless of name

:The name scope delimiter, separating the name scope prefix from the element or attribute name !*Apply the specified method () * Group on the related node to explicitly specify precedence [] apply the filter style []* subscript operator to indicate the element in the collection

Table II, logical operators

Optionally describes and $and $ or && logical with or $or $ or | | Logical or Not () $not $ logical Non

Table III, relational operators

Optional Description = or $eq $ equality = or $ieq $ equality (case-insensitive)!= or $ne $ unequal $ine$ (case-insensitive) < or $lt $ less than $ilt$ (case-insensitive) <= or $le $ less than or equal to $ile$ less than or equal (no size Write) > or $GT $ greater than $igt$ (case-insensitive) >= or $ge $ greater than or equal to $ige$ is greater than or equal to (case-insensitive) $all $ set operator, returns the true $any $ set operator if all items in the collection meet conditions. Returns the "true" | Collection operator if any item in the collection satisfies a condition, returning a union of two sets

Example one:

Look for the name and e-mail from your resume for people with "web development" skills. Suppose the document structure looks like this:

<document>
<resume>
<name>name</name>
<sex>sex</sex>
<birthday>birthday</birthday>
<skill>skill1</skill>
<skill>skill2</skill2>
...
<skill>skilln</skill>
</resume>
<resume>
...
</resume>
...
</document>

The XSL document structure for the names and e-mail of all the people who have web development skills is found in the above-structured personal resume as follows:

<table border= "1" cellspacing= "0" >
<TH> name </TH><TH>E-Mail</TH>
<xsl:for-each select= "Resume [$any $skill=" web Development "]" >
<tr><td><xsl:value-of select= "Name"/></td>
<td><xsl:value-of select= "e-mail"/></td>
</TR>
</xsl:for-each>
</TABLE>

Description

1.[]── Indicates the selection condition, only the resume that satisfies the condition is displayed.

2. $any $── Because each person has a variety of skills, so add $any$ as a prefix so that everyone's skills can be compared.

3.skill= ' web Development '--filter criteria.

Example Two,

Still, for example, the XML document above, if you want to select the name, skills, and e-mail of the person born before 1977/1/1, the corresponding XSL document structure is as follows (assuming the birthday format is YYYY/MM/DD):

<table border= "1" cellspacing= "0" >
<TH> Name </TH><TH> Skills </TH><TH>E-Mail</TH>
<xsl:for-each select= "resume[birthday$lt$" 1977/1/1 "]" >
<TR>
<td><xsl:value-of select= "Name"/></td>
<TD>
<xsl:value-of select= "skill[0]"/>
<xsl:for-each select= "Skill[index () >0]" >,
<xsl:value-of select= "." />
</xsl:for-each>
</TD>
<td><xsl:value-of select= "e-mail"/></td>
</TR>
</xsl:for-each>
</TABLE>

Description

1.birthday $lt $ ' 1977/1/1 '-search conditions where "<" is an error, using "$lt $" to represent less than.

2.skill [0]── represents the first item to select Skill.

3.skill [Index () >0]── represents items that have been selected after the second item of skill (including the second item).

4.xsl:value-of select= "."--to select the value of the current tag.

I believe you should note that some functions, such as index (), Formatindex (), and Childnumber (), may not be fully understood in the preceding and present examples. Please pay attention to the next lesson. [Page]

This period learns about XSL style methods for use with the select Properties of XSL elements <xsl:for-each>, <xsl:value-of>, <xsl:template>, <xsl: Apply-templates> 's match properties, <xsl:if>, <xsl:when> test Properties, filter the scope of the element to provide greater flexibility.


XML is like DHTML (Dynamic HTML), these nodes are all objects, and these objects are layered, starting from the root node to form a hierarchical clear tree structure, which forms the Document Object model DOM, which is based on the object's properties, method to achieve the purpose of accessing the control XML node.


We are not going to elaborate on the XML DOM in detail, as it can be written in a more extensive tutorial, and we'll discuss some common methods to get a general idea of the DOM's object approach.

Note: From the beginning of this period, all samples no longer provide complete source code, if you do not understand, please read the previous seven, and practicing.

One, End ()

Meaning: Returns the last element in the collection.

Example: Output last Resume

Suppose the XML file format is:

... <resume>...</resume>......<resume>...</resume> .......

The contents of the corresponding XSL file are:

<xsl:for-each select= "Resume[end ()]" >......</xsl:for-each>

Or:

<xsl:templates match= "Resume[end ()]" >......</xsl:templates>

Or:

<xsl:apply-template select= "Resume[end ()]" >......</xsl:apply-template>

Second, index ()

Meaning: Returns the position of the element in the collection, and the return value is an integer in which the first element returns 0.

Example: Return to the previous three resumes.

Resume[index () $le $]

Note: index () is related to the parent element, see the following example:

<x>
<y/>
<y/>
</x>
<x>
<y/>
<y/>
</x>

Returns the first <y> in all <x>

X/y[index () =0] or x/y[0]

Third, nodename ()

Meaning: Returns the name of the element, which is the tag name.

Example: Select any element, if its name (that is, the tag name) equals "name":

*[nodename () = ' name '] or *[name]

Four, number ()

Meaning: Converts a value to a numeric form and returns null if it is not a value, requiring parameters.

Example: CV of person aged (age) less than 30 years old (resume):

Resume[number (age) $lt $] or resume[age$lt$30]

V. NodeType ()

Meaning: Returns the node type, resulting in a numeric value. The following is a list of return values:

The character form of node type node type value node description element 1 ' element ' element attribute 2 ' attribute ' markup-delimited Region of text 3 ' text ' Processi ng instruction 7 ' processing_instruction ' Comment 8 ' Comment ' document Entity 9 ' document '

VI, Value ()

Meaning: Returns the value of an element or attribute.

Example: Value () is the default method for an element or attribute, and the following representation is equivalent:

Name!value () = "name" and name= "name"

@attr = "Attribute_value" and @attr = "Attribute_value"

Note: @ is the attribute prefix, @attr representation is the attribute attr

Seven, attribute ()

Meaning: Returns the collection of all attribute nodes, equivalent to "@*".

Example: Look for all resume elements that satisfy a condition with at least one attribute with the value "ABC":

resume[$any $attribute () = ' abc '] or resume[$any $@*= ' abc ']

Look for all the resume elements that meet the criteria at least one child element has an attribute with a value of "ABC":

resume[$any $*/attribute () = ' abc '] or resume[$any $*/@*= ' abc ']

Viii. Comment ()

Meaning: Returns all annotation nodes.

Example:

resume[$any $comment () = ' CV of Yu Hillian ']

Represents a <resume> element that looks for a CV that contains comment statements:<!--Yu Hillian.

Nine, CDATA ()

Meaning: Returns a collection of nodes of all CDATA types.

Example:

resume[$any $cdata () = ' CV of Yu Hillian ']

Indicates that the search contains the following statement (must be a direct child node) <! [cdata[Euchierne's resume]]> 's <resume> elements.

Ten, Node ()

Meaning: Returns the collection of all nodes except the root node and the attribute node in the current context, equivalent to:

"*|pi () |comment () |text ()"

Example: Find all element resume with the name "skill" of the last node:

Resume[node () [End ()]!nodename () = ' skill ']

Find the first node for all resume elements: Resume/node () [0].

Xi. Textnode ()

Meaning: Returns a collection of nodes of all text types.

Example: Find the second text node for each P element:

P/textnode (1) or P!textnode (1)

12, TEXT ()

Meaning: Returns a collection of all nodes representing the text string, equivalent to "CDATA () |textnode ()".

The content of this issue is introduced to this point, another function date () on my machine a try on the error so that the browser automatically shut down, there is a function pi () I have not found the appropriate application method, it is not introduced, the next period will describe how to use the script in the XSL. [Page]

Sometimes, we might want XML documents to be output with some statistical information or something like numbers, and it's not easy to make use of the previous knowledge. Two new elements <xsl:eval> and <XSL:SCRIPT> will be introduced today, so that we can easily handle this challenge.

<xsl:eval>

Meaning: Computes a script expression, outputting a text string.

Grammar:

<xsl:eval language= "Language-name" >

Property:

language── the name of the scripting language used, the available attributes are "JavaScript", "JScript", "VBScript", "VBS", and so on, and the default is "JScript".

<xsl:script>

Meaning: Declares a global variable or defines a function.

Grammar:

<xsl:script language= "Language-name" >

Properties: With <xsl:eval>


Example:

I wonder if you still have an impression of the example in the fourth issue of "Learning xml"? The XML document does not have a resume number, but the output has an uppercase Roman numeral ordinal. A slightly more complicated example will be cited today:

If we write a year-end production table, which requires a subtotal, the usual practice is to calculate it in advance, now do not have to, we can only give a single statistic, display when the subtotal one. Please find the fourth phase of "Follow me xml", the XML file does not have to be modified, and the XSL file is modified as follows:

<?xml version= "1.0" encoding= "GB2312"?>
<xsl:stylesheet xmlns:xsl= "Http://www.w3.org/TR/WD-xsl" >

<xsl:template match= "/" >
<body><xsl:apply-templates select= "Document"/></body>
</HTML>
</xsl:template>

<xsl:template match= "Document" >
<table border= "1" cellspacing= "0" >
<TH> Team </TH>
<TH> First quarter </TH>
<TH> Two quarterly </TH>
<TH> Three quarterly </TH>
<TH> Four Quarterly </TH>
<xsl:apply-templates select= "The/>"

<TR><TD> Subtotal </TD>
<td><xsl:eval>total (This, "Q1") </xsl:eval></TD>
<td><xsl:eval>total (This, "Q2") </xsl:eval></TD>
<td><xsl:eval>total (This, "Q3") </xsl:eval></TD>
<td><xsl:eval>total (This, "Q4") </xsl:eval></TD>
</TR>


</TABLE>

<xsl:script>
function Total (node,q)
{
Temp=0;
mark= '/document/report/' +q;
V=node.selectnodes (Mark);
For (T=v.nextnode (); T;t=v.nextnode ())
{
Temp+=number (T.text);
}
return temp; Subtotal value
}
</xsl:script>

</xsl:template>

<xsl:template match= "the" >
<TR>
<td><xsl:value-of select= "Class"/></td>
<td><xsl:apply-templates select= "Q1"/></td>
<td><xsl:apply-templates select= "Q2"/></td>
<td><xsl:apply-templates select= "Q3"/></td>
<td><xsl:apply-templates select= "Q4"/></td>
</TR>
</xsl:template>

<xsl:template match= "Q1|q2|q3|q4" >
<!--here to test output, such as less than or equal to 20, add a style property color with red (red)-->
<xsl:if test= ". [Value () $le $] >
<xsl:attribute name= "Style" >color:red</xsl:attribute>
</xsl:if>
<xsl:value-of/>
</xsl:template>

</xsl:stylesheet>


What the previous example looks like in a browser (IE5.0 or later)

Description

Do you notice any changes in the execution results? In the bold part for the add part, note that the add part is divided into two parts,<xsl:script></xsl:script> must be placed after </TABLE>, remember.

SelectNodes ()--is a Xmldomobject method that returns the set of all nodes in the document that satisfy the condition, and the conditions are the same as the values of the < Xsl:for-each > and select Attributes, and can be filtered, subscript, etc. For teams with a quarterly yield greater than or equal to 50:

/document/report/q1[value () $ge $50]

The above wording has a simpler wording:

Q1[value () $ge $]

Indicates that all nodes are traversed from the root node to find the node that satisfies the condition, and it is not advisable to use this method if there are nodes with the same name but different meanings in the document. In this case, if you want to see the total annual production, you can find a node in the following string (the last one is recommended, and the description will pinpoint the data that needs to be summarized):

*[value () $gt $] OR//(Q1|Q2|Q3|Q4) or/document/report/(Q1|Q2|Q3|Q4)

NextNode ()--Returns the next node in the node set

Number ()-Converts the supplied argument to a numeric value


The next issue is about XSL function 2, for <xsl:script> and <xsl:eval>, and for the expr properties of <xsl:if> and <xsl:when>. It is recommended that the reader be familiar with at least one of the JavaScript, JScript, and VBScript, and that no work you can do with XSL will be very limited. Due to the length of the relationship, no details are given here. [Page]

This issue introduces multiple XSL methods and properties for VBScript, JScript, to give full play to XML advantages, for <xsl:script>, <xsl:eval> markup expression writing or <xsl:if>, The expr attribute of <xsl:when>.

First, Absolutechildnumber

Meaning: Returns the ordinal number of a node relative to all its siblings, regardless of the name.

Syntax: Absolutechildnumber (node)

Parameters: node── object, to return the number of nodes.

Example:

1, assuming that the document structure is: <DOCUMENT><HEAD/><BODY/></DOCUMENT>, where documents are top-level nodes, the following expression will be output:

<xsl:eval>
Absolutechildnumber (This.selectnodes ('/document/body '). Item (0))
</xsl:eval>

2. Determine the serial number of the current node relative to all of its brothers:

<xsl:eval>
Absolutechildnumber (This)
</xsl:eval>

Second, Ancestorchildnumber

Meaning: Returns the ordinal number of the nearest ancestor node (relative to the same node) based on the given ancestor node name, starting at the given node. Returns 0 if the ancestor is not found.

Syntax: Ancestorchildnumber (Bstrnodename, Pnode)

Parameters:

bstrnodename── string. The name of the ancestor node being searched.

pnode── object. The node where the search starts.

The example finds the nearest node named the statement ancestor node:

Ancestorchildnumber (' The ", this)

Third, attributes

Meaning: Returns a collection of node attributes.

Syntax: object.attributes

Parameter: object── Node object.

Example: Number of current node properties

This.attributes.length

The value of the third property of the current node

This.attributs.item (2). Value

Or

This.attributes.item (2). Text

Or

This.attributes (2). Text

Note: If the given subscript is larger than the property sum minus 1, the subscript for the first property is 0.

Four, BaseName

Meaning: Returns the base name with namespace restrictions, excluding the name prefix.

Syntax: Object.basename

Parameters: object── Node Object

example, the base name of the current node:

This.basename

Five, Childnumber

Meaning: Returns the ordinal number of a node relative to a sibling of the same name.

Syntax: Childnumber (object)

Parameters: object── Node Object

example, assume that the XML document is structured as follows:

<x><y><z></z></y></x>

If the current node is Z, Childnumber (this) returns 1, and Absolutechildnumber (this) returns 3.

VI. DataType

Meaning: Sets or reads the data type of the node.

Syntax: Setting the data type of a node Object.datatype=objvalue
Read the data type of the node Objvalue=object.datatype

Parameter: object── Node object.

example, to read the data type of the current node:

Dttype=this.datatype

Seven, depth

Meaning: Specifies the depth at which the node appears on the document tree, where the node is at the top level of the document, the top-level node is at the first level, and the root node (that is, the node represented by "/") is at the No. 0 level.

Syntax: Depth (pnode)

Parameters: pnode── Node Object

example, the depth of the current node:

Depth (this)

Viii. FirstChild, LastChild

Meaning: Returns the first child node (or last child node) of a node.

Syntax: Pnode.firstchild
Pnode.lastchild

Parameters: pnode── Node Object

example, the name of the first node of the current node:

This.firstChild.nodeName

Nine, Formatindex

Meaning: The supplied integer is formatted with the specified count system.

Syntax: Formatindex (lindex, Bstrformat)

Parameters:

lindex── integer value or variable

bstrformat── data format, the optional values are a, a, I, I, 1, 01 (the numeric form preceded by 0, which is useful if a fixed-length number such as 0001, 0002 is required).

example, uppercase Roman numeral number for the current node:

Formatindex (Childnumber (this), ' I ')

Ten, FormatNumber

Meaning: Outputs a value in the specified format.

Syntax: FormatNumber (Dblnumber, Bstrformat)

Parameters: The description is the same as FormatNumber, except that the format can be decimal.

example, the value of variable A is formatted as two decimal places:

FormatNumber (A, ' #.00 '):

Xi. HasChildNodes

Meaning: Returns True (-1) If the node has a child node, or False (0).

Syntax: Pnode.haschildnodes ()

Note: Unlike the function described earlier, this function must be preceded by an empty bracket.

Example to determine whether the current node has a child node:

This.haschildnodes

12, NamespaceURI, prefix

Meaning: Returns the global resource identifier (or prefix) of the node namespace.

Syntax: Pnode.namespaceuri
Pnode.prifix

13, NextSibling, PreviousSibling, parentnode

Meaning: Returns the next sibling of the node (or the parent node of the previous sibling, or node).

Syntax: pnode.nextsibling
Pnode.previoussibling
Pnode.parentnode

Note: Applying the ParentNode method to the root node (that is, "/"), applying the PreviousSibling method to the first child node, and applying the NextSibling method to the last child node will result in an error that can be passed through the relational operator = = (equals) and the!= (Not equal) to determine whether a node is a specified node, in the form of pNode1 = PNode2 or PNode2!= pNode2.

14, NodeName

Meaning: Returns a specific string of elements, attributes, entry names, or other types of nodes.

Syntax: Pnode.nodename

example, the name of the current node:

This.nodename

XV, NodeType, nodetypestring

Meaning: Returns the numeric form (or string form) of the type of the node.

Syntax: Pnode.nodetype or pnode.nodetypestring

return value:

The character form of node type node type value node description element 1 ' element ' element attribute 2 ' attribute ' markup-delimited Region of text 3 ' text ' Processi ng instruction 7 ' processing_instruction ' Comment 8 ' Comment ' document Entity 9 ' document '

16, nodeTypedValue

Meaning: Returns the value of a node as a node-predefined data type.

Syntax: Pnode.nodetypedvalue

example, assuming that the data type of the current node is fixed.14.4, the following example returns the value of the node as a number, rather than a string of text:

This.nodetypedvalue

17, NodeValue

Meaning: Returns the text of a node.

Syntax: Pnode.nodevalue

Note: This method is not used for element class nodes and can be used for properties, CDATA, annotations, text, and so on.

example, the value of the first property of the current element:

This.attributes (0). nodevalue

The text within the current element (assuming that there is only text in the element, no other element, that is, <mark>text</mark> it is recommended to try to master its exact usage several times).

This.firstChild.nodeValue

18, Ownerdocument

Meaning: Returns the root of the document that contains the node.

Syntax: pnode.ownerdocument

Note: This method is used for document root node errors.

19, SelectNodes

Meaning: The given style match applies to the current node and returns a matching set of nodes.

Syntax: pnode.selectnodes (' pattern ')

Tip: Pattern writing is similar to the value of the Select property of <xsl:for-each>, which starts with "/" to search from the root of the document, and traverses all nodes of the document with the "//" Start table; The beginning represents the start of the parent node of the current node, and cannot have the above special characters if you want to search down from the current node.

example, the number of elements with the same name as the current node within their parent element:

Childnumber (This.selectnodes) (". /"+this.nodename+" [end ()]]. Item (0))

The number of elements in the current element whose name is "skill":

Childnumber (This.selectnodes ("Skill[end ()]"). Item (0))

20, selectSingleNode

Meaning: Similar to selectnodes, different returns only the first node that matches, not the set of nodes.

Syntax: Pnode.selectsinglenode (' pattern ')

example, the number of elements with the same name as the current node within their parent element:

Childnumber (This.selectsinglenode) (". /"+this.nodename+" [end ()]))

The number of elements in the current element whose name is "skill":

Childnumber (This.selectsinglenode ("Skill[end ())")

21, text

Meaning: Returns the text content within the node and its subtree.

Syntax: Pnode.text

example, text content throughout the document:

This.ownerDocument.text

The text content of the current element and its subtree:

This.text

22, XML

Meaning: An XML representation that returns the node and its descendants.

Syntax: Pnode.xml

example, the XML content of the current document:

This.ownerDocument.xml

A few other functions are not introduced, listed below for reference, such as interested, please visit http://msdn.microsoft.com for detailed instructions.

Formattime (Vartime, Bstrformat,vardestlocale)
FormatDate (Vardate, Bstrformat,vardestlocale)
Apendchild (newchild)
Definition
CloneNode
InsertBefore (newchild, Refchild)
Parsed
RemoveChild (Oldchild)
ReplaceChild (newchild, Oldchild)
Specified
Transformnode (stylesheet)
transformNodeToObject (Stylesheet,outputobject)
UniqueID (Pnode)



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.