XSLT is easy to get started

xiaoxiao2021-03-06  54

XSLT is easy to get started

1.1 What is the English standard name of XSLT XSLT is Extensible Stylesheet Language Transformation. According to the W3C specification manual (http://www.w3.org/tr/xslt), the earliest design of XSLT is to help the XML document (Document) to convert to other documents. However, with the development, XSLT is not only used to convert XML to HTML or other text formats, and more comprehensive definitions should be: XSLT is a language for converting the XML document structure. 1.2 Why do we already know with XSLT, XML is a simple and standard approach to exchange raw data between computer programs. Its success is not that it is easily written and read, more importantly, it fundamentally solves information exchange between the application system. Because XML meets two basic needs: (1). Separate data and expression. Information on weather forecasts can be displayed on different devices, television, mobile phones or others. (2). Transfer data between different applications. E-commerce data exchange has increasing the need to make this demand increasingly urgent. In order to make the data easy to understand, we need to display the information or print out, such as turning data into an HTML file, a PDF file, even a sound; also, in order to make data suitable for different applications, we must There is an ability to convert a data format to another. For example, the demand format may be a text file, a SQL statement, an HTTP information, a certain order of data calls, etc. And XSLT is the language we used to implement this conversion function. Convert XML to HTML, which is currently the most important function of XSLT. 1.3 XSLT history Thought many other XML family members, XSLT drafted and developed by W3C. Its main development has been as follows:. Proposed by James CLARK in 1995; officially proposal in August 1997 is XSL;. In May 1998, the demand summary was completed by Norman Walsh; on August 18, 1998, issued; .1999 The XSL 1.0 recommended version was officially released on November 16. At present, XSLT is still in rapid development, and the draft XSLT1.1 can be seen on the W3C website (http://www.w3.org/tr/xslt11). 1.4 What is XPath XPath is an important part of XSLT, and we will explain its detailed grammar in Chapter 4. So what is XPATH? Let's take a look at the "family" relationship of the XSL series. As shown below:

XSL is divided into obvious two processes when converting XML documents, and the first conversion document structure; secondly formats the documentation. These two steps can be separated and processed separately, so XSL gradually split into XSLT (Structure Translation) and XSL-FO (Formatting Objects) in the development process, and XSL-FO's role Similar to the role of CSS in HTML. And we focus on discussing the first step in the first step, that is, XSLT. In addition, we already know that XML is a complete tree structure document when learning XML. In the conversion XML document, you may need to process some (node) data, so how to find and locate the information in the XML document, XPath is a language specifically used to find information in the XML document. XPath is affiliated with XSLT, so we usually mix the XSLT syntax and XPath syntax. Using a more good understanding: If the XML document is viewed as a database, XPath is a SQL query language; if the XML document is viewed as a DOS directory structure, XPath is a collection of CD, DIR and other directory operation commands. 1.5 XSLT and CSS comparison CSS can also format XML documents, then why do CSS still need XSLT? Because CSS can control the style of the output, such as color, font, size, etc., it has a serious limitations, that is: (1) CSS cannot reorder the elements in the document; (2) CSS cannot judge and control Which element is displayed, which is not displayed; (3) CSS cannot statistically calculate data in the element; in other words, CSS is only suitable for outputting a relatively fixed final document. The advantage of CSS is simple, consumes less system resources; while XSLT is powerful, but because the XML tree is required, it is more memory. Therefore, we often combine them, such as using the XSLT processing document in the server, controlling the CSS. Can reduce the response time. 1.6 XSLT and IE5 released in the XSLT draft shortly, Microsoft provided a preview version that supported XSL function in IE4, which officially supported XSLT when IE5.0 was released, but because IE5 released than XSLT1.0 standard time early, The XSTL feature supported in IE5.0 is slightly different from XSLT 1.0. (呵 ~~~ One of the main reasons for XML is to solve the problem of HTML over-dependent browser, now Microsoft wants to work newly.). The standards performed in Microsoft IE5.5 have been substantially similar to the XSLT1.0 of W3C. But a headache is that IE5.0 has released millions of sets, and the XSLT you use is likely to be executed correctly by the customer's browser. At present, XSLT 1.1 is still in development, W3C and related organizations have also got unified with Microsoft negotiation. Ha ha ~~ The story is still not ending. Note: The grammar mentioned herein is based on the standards of XSLT 1.0, without any "dialect" of Microsoft. 2.XSLT Example 2.1 How XSLT converts XML We play an interesting part, you play the plasticine, press the different molds to make a needed shape. If we assume that the XML data document is a big plasticine, XSLT is like a mold, and it is necessary to make a needed shape. We entered the XML original document, use XSL as a template, through the conversion engine, the final output required HTML document. The conversion engine is the process of "force one according to force" in the metaphor.

In specific applications, there are special software to implement this conversion process, named XML Processor. There is already a lot of Processor software (hereinafter referred to in detail below), and XML Processor has been embedded in IE5.5. 2.2 An instance Now let's take a simple XSLT actual application example to get some sense of understanding. Many web designers see the code similar to HTML will be relieved, the code is kind and familiar. Example 1: "Hello, World!" Hello World as the first tutorial is already a practice in the program language. We also follow this practice to see how to use XSLT to display "Hello World". Although this example doesn't have any practical use, please don't worry, there is more detailed example. Step 1: Create to enter the XML document Hello.xml. Hello, World! This is a very simple XML document that contains only a node XML tree. Step 2: Establish a XSLT document Hello.xsl. Tip: The default XSLT file has the name of .xsl. first xslt example </ title> </ head> <body> <p> <xsl: value-of select = "greeting" /> </ p> </ Body> </ html> </ xsl: template> </ xsl: styleSheet> You can now open this hello.xsl file with IE5.0 or above, see the XSL tree. Step 3: Call this XSL file in XML. Modify Hello.xml code is: <? XML Version = "1.0" encoding = "ISO-8859-1"> <? Xml-stylesheet type = "text / xsl" href = "hello.xsl"?> <Greeting > Hello, World! </ Greeting> OK, all code has been completed in principle, followed by using an XSLT processor (XML processor) to perform Hello.xml, you can see "Hello World" The result is displayed. The popular processor software has the following: (1) .james Clark XT. Download Website: http://www.jclark.com/xml/xt.html (2) XML for Java package named LotusxSL. Download Website: www.alphaworks.ibm.com/tech/xml4j (3) .saxon.</p> <p>Download URL: http://www.wrox.com (4). Microsoft's MSXML3. Download URL: http://www.microsoft.com/xml Some netizens should ask, I want to see what the "Hello World" is doing in the browser? In Microsoft's IE5.5 embeds the MSXML3 interpreter, you can use IE5.5 to open the Hello.xml file, you can see the result. If you only see the XML tree, not a separate "Hello World" word, indicating that your browser does not have MSXML3 version. What should I do if I don't want to see it? Then use the old approach in our XML tutorial, use JS implementation. (This has exceeded the scope of this article, but in order to be more intuitive, we provide example code here.) The following is an implementation code that can be saved as hello.htm, Hello.xml, Hello .xsl is placed in the same directory. Finally, you can see the effect with IE5.0 or later. <html> <head> <script language = "javascript" for = "window" Event = "online"> var xmldoc = new activXObject ("Microsoft.xmLDom"); xmldoc.async = "false"; xmlDoc.Load (" Hello.xml "); nodes = xmldoc.documentelement.childNodes; greeting.innertext = nodes.Item (0) .text; </ script> <title> first xslt example </ title> </ head> <body bgcolor =" #Fffffff> <span id = "greeting"> </ span> <br> </ body> </ html> 2.3 Process resolution If you succeed, you may want to know the specific meaning of these code, let's come Detailed explanation: See hello.xsl file <? XML Version = "1.0" encoding = "ISO-8859-1"> This is the first line code of the standard XML document, because the XSLT itself is also an XML document. Encoding properties are used to define the form of coding usage, ISO-8859-1 mainly supports Western Europe and North American language coding. If you want to use Simplified Chinese, you should write: <? XML Version = "1.0" Encoding = "GB2312"?> The next code is: <XSL: Stylesheet XMLns: XSL = "http: //www.w3. ORG / 1999 / XSL / Transform "Version =" 1.0 "> This is the standard XSLT file first line code. XSL: Stylesheet code means processing documents as a style sheet (STYLESHEET).</p> <p>XMLns: XSL attribute is a namespace declaration, as in XML, using methods in XML, to prevent element name repetition and confusion. Where the prefix XSL means that the elements used in the document abide by the W3C's XSLT specification. The last Version property Description Style Table is only the standard function of XSLT 1.0, which is also currently only standard. <XSL: Template Match = "/"> A <XSL: Template> element defines a template rule. Property Match = "/" Description XML source document, the starting point for this template rule. "/" Is an XPath syntax, which will be described in detail later, "/" "/" represents the root of the XML tree (root). The next code is: <html> <head> <title> first xslt example </ title> </ head> <body> <p> <xsl: value-of select = "greeting" /> </ p> < / body> </ html> Description: When the template rule is triggered, the content of the template will control the result of the output. In the example, most of the template is composed of HTML elements and text. Only the <xsl: value-of> element is a XSLT syntax, where <XSL: value-of> is the role of <XSL: value-of> is to copy the value of a node in the original document to the output document. The select property specifies the node name to be processed in detail. This is the XPath syntax, "greeting" means looking for elements named Greeting, and manages this node with template. Specifically, find the <greeting> element, then copy the value of the element to the output file in the template style. Tip: Since the XML document is a strict hierarchy (view XML file with IE5, you will see the XML document similar to multi-level associated menu), so our image is called the XML document as a document tree, which is called a node of the tree. . The root element is root node. Finally close all elements: </ XSL: Template> </ xsl: style ,,,,,,,,,,,,,, Have you thought about why you want to use such a complex way to display "Hello World"? The key is not on the surface, but in the substance: use this method, Hello World can be extracted from the XML document and use a variety of different XSLT template processing to output documents of different needs. Let's take a look at the main use of XSLT: 2.4 The main use of XSLT XSLT is the data conversion application. Due to XML-based e-commerce, XSLT is also increasingly important as data conversion roles. For example, directly convert the data format of TV news into data format required for newspaper news; direct converting the stock data into a picture display on the web; statistics, sorting the EDI (electronic data exchange) data. XSLT is an ideal tool for processing similar work.</p> <p>3. xi-Template and XSL: Apply-Templates Templates (Template) is one of the most important concepts in XSLT. The XSLT file consists of a template, and any XSLT file contains at least one template. The concept of template is like a wooden; if you are a programmer, you can also treat a template as a method, a class, or a module. They can be assembled, or they can be made separately, different templates control different output formats. Template consists of two parts: match pattern and execution. Simple lecture mode Defines which node in the XML source document will be processed by template, and execute what format is defined. Two parts of the corresponding syntax for XSL: Template and XSL: Apply-Templates. XSL: Template's syntax is: <XSL: Template Match = pattern name = qname priority = number mode = qname> <! - Execute content -> </ xsl: template> XSL: template's role is to define a new template. In the property, Name, Priority, and Mode are used to distinguish different templates that match the same node. They are not common attributes. Match property controls the matching mode of the template (Pattern), the matching mode is used to locate which node is handled by the template in the XML source document. A template matches a node. We use an example to help understand: Suppose we have to handle a document containing chapters and paragraphs. We define paragraphs with the PARA element and define chapters with Chapter Elements. Let's take a look at the possible value of the Match property. The following statement means template matches all para elements <xsl: template match = "para"> </ xsl: template> The following statement write Description Template matches all Para elements and all Chapter Elements: <xsl: template match = "(Chapter | Para)> </ xsl: template> The following statement Word Description Template Matches all PARA elements for the Chapter element: <xsl: template match =" chapter // Para "> </ xsl: template > The following statement means template matching root node: <xsl: template match = "/"> </ xsl: template> Let's see Apply-Templates Syntax: <XSL: Apply-Templates SELECT = Node Set-Expression Mode = QNAME > </ Xsl: Apply-Templates> XSL: Apply-Templates is used to perform that node is handled by template. You can understand it as a subsidy in the program. SELECT property is used to define the exact node name.</p> <p>XSL: Apply-Templates is always included in the XSL: Template element, like this: <xsl: template match = "/"> <xsl: Apply-Templates select = "para" /> </ xsl: template> This code Note The touchpad matches the entire document (root node), and all PARA elements under the root node are processed when executed. <XSL: Template Match = "Para"> <p> <xsl: Apply-Templates /> </ P> </ XSL: Template> This section means that the touchpad matches the Para node, all the child elements under all PARA Will be processed. 3.2 XSL: Value-of XSL: value-of is used to write text values ​​of elements in the source document to the output document. For example: there is an XML document for personal information: <? XML Version = "1.0" eNCoding = "ISO-8859-1"> <Person> <name> ajie </ name> <agn> 28 </ age> </ Person> I want to display the value of the Name element in the XML source document in the output document, you can write XSLT code this: <xsl: template match = "person"> <xsl: value-of select = "name" / > </ Xsl: Template> After execution, you will see "Ajie" is displayed separately. Where match = "person" defines the touchpad matching the Person node, XSL: value-of syntax description requires the value of a node, and select = "name" defines the elements that need to be output as Name. Is it true that this process is not a person's name in the database? Of course, XSL: value-of query has more, more complex syntax, because it is related to the function of looking and positioning, we will put it in the following XPath syntax in a careful explanation. The same functions have XSL: Copy-of, the same, the same, it is not repeated. 3.3 XSL: for-Each XSL: for-EACH Syntax Allows you to loop processing selected nodes.</p> <p>For example: there is an XML document containing multiple people: <? XML Version = "1.0" eNCoding = "ISO-8859-1"> <people> <person> <name> ajie </ name> <agn> 28 </ age> </ person> <Person> <name> Tom </ Name> <ag> 24 </ age> </ person> <Person> <name> Miable </ name> <agn> 30 </ agn> <Age> 30 </ age> </ Person> </ people> I need to display the name of the owner, you can write the XSLT code into: <xsl: template match = "people"> <xsl: for-each select = "child :: Person> <XSL : value-of select = "name" /> </ xsl: for-each> </ xsl: template> 3.4 xsl: if xsl: if the IF condition statement like a normal program language allows the setting node to meet a certain condition Template. XSL: The syntax format of the IF is: <xsl: if test = Boolean expression> template body </ xsl: if>, for example: <xsl: template match = "people"> <xsl: if test = "@ name"> < P> <xsl: value-of select = "@ name" /> </ p> </ xsl: if> </ xsl: template> This code means detecting all the elements under the PEOPLE node, if you find Name> Elements, output the value of the <name> element. Where @ 号 is a consecutive, representing all the elements under the node. 3.5 XSL: Choose, XSL: WHEN and XSL: OtherWise XSL: IF syntax does not have an attribute of ELSE. If we want to do multiple options, then use XSL: Choose / XSL: WHEN / XSL: OtherWise Series Process Control Syntax.</p> <p>Specific use Please see the following XSL file example: <xsl: template match = "people"> <xsl: choose> <xsl: when test = "@ name = 'ajie'"> <b> <xsl: value-of Select = "@ Name" /> </ b> </ xsl: by> <xsl: when test = "@ name"> <i> <xsl: value-of select = "@ name" /> </ i> </ xsl: when> <xsl: OtherWise> No name available </ xsl: OtherWise> <xsl: choose> </ xsl: template> Description: First look for the <name> attribute value as a JIE, if you are in the PEOPLE Found, use the Ajie to output; if there is no <name> element that is found to be Ajie, all <name> elements are output; if no <name> element is found, "NO NAME Available. 3.6 XSL: SORT can reorder the elements of the XML source document in XSLT, and the syntax sorted is XSL: Sort. Example: The following code is to place the document element by NAME. <XSL: Template Match = "People"> <xsl: Apply-Templates Select = "Person"> <XSL: Sort Select = "@ name" /> </ xsl: Apply-Templates> </ xsl: template> above The primary grammar of the element of the XSLT, there are many other grammar, such as Import, include, Element, Attribute, Number, Param, etc., which are not explained here. Our goal is to let you have basic concepts of XSLT's syntax, understand XSLT as a powerful function of conversion languages. 4. XPATH Syntax We have already mentioned above, XPath is the language used to help XSLT to find location information in the XML source document. During the actual use, XPath and XSLT are always mixed together. In the above chapter, we already have the syntax used to use XPath, just not clearly. But W3C divides them into two standards, so we also dismantled them into two chapters to explain. 4.1 Current location When we use the XSLT to process the XML source document, we use context to represent the node location that is currently being processed by the template. For example, the XSL: Template match = "/" statement indicates the root node of the document in the document. I don't know how to accurately translate the word word, which is similar to the pointer in the C language, indicating the location where the program is currently running. Understanding Context is very important to correctly handle the XSL template, when your XSL template outputs, the first thing you want, the first should be analyzed where CONTEXT is. Location Paths is used to set the CONTEXT node location you want to find.</p> <p>Similar to the DOS directory command. We look an example <xsl: for-each select = "child :: people / descendant :: Person"> where Child :: people / descendant :: Person is xpath syntax, this expression is a location paths, code description to display The child elements of all People elements and child elements of all Person elements. Usually we will use simpler ways: <xsl: for-each select = "people // person"> We explain two representations of PATH: "/" and "//". "/" Is a node that represents the current document, similar to the DOS directory split. For example: / people represents the people elements under the root node; People / Person represents all the Peson sub-elements under the people. "//" means all nodes of the current document. Similar to view the entire directory. For example: // people indicate what the people have all in the document, whether it is what level; people // person represents all the Person elements under the people of the People, no matter how deep it. 4.2 Addressing Operation AXIS and PREDICATE is the syntax for positioning the Location Paths in the XPath syntax, and the specific usage list is as follows syntax table -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------- Expressive Description ------------ ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Self. Select the current node . Example: <TD> <XSL: Value-of select = "." /> </ Td> code means inserting the current node included in the current location, ----------- -------------------------------------------- parent .. Select the current The parent node of the node. -------------------------------------------------- ------ Attribute @ Select all properties of an element. Example: <TD> <XSL: Value-of select = "@ personid" /> </ td> Select all properties of the Person element. -------------------- ---------------------------------- Child Select all child elements of the current node. -------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------ AXIS helps us choose all the nodes around the current node, and Predicate is used to locate the current node inside Elements. Representation is square bracket [] plus expression: [expression].</p> <p>Specific examples are as follows: Person [position () = 2] This code indicates that the second "Person" element Person [starts-with (name, "b")] This code means looking for all names starting with "B" Person element. 4.3 Operators This section introduces the EXPRESSIONS, the list is as follows: -------------------------------- ------------------------ Operator Description ----------------------- -------------------------------- And, OR is the ordinary meaning and, or ------- ------------------------------------------------- = Isotherm to ------------------------------------------------- -------! = Not equal to --------------------------------------- ----------------->,> = greater than, greater than or equal to ------------------------- ------------------------------ <, <= less than, less than or equal. Note: In the XSL file, <indication should be <Representation -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------- , -, *, DIV Dimension and Summary --------------------- ----------------------------------- MOD mode ------------ -------------------------------------------- | Two nodes together -------------------------------------------------- ------ 4.4 Functions (Functions) There are many function functions in XPath to help us find the nodes you need. Count () function: Statistical count, returns the number of qualified nodes. Example: <p> <xsl: value-of select = "" /> </ p> Description: The purpose of the code is to display a few name attribute values ​​in the Person element. Number () Features: Convert text in the value of the property to a value. Example: <p> The number is: <xsl: value-of select = "Number (Book / Price)" /> </ p> Description: The use of the code is the price of the display. Substring () Function Syntax: Substring (Value, Start, Length) Role: Intercept string. Example: <p> <xsl: value-of select = "Substring (Name, 1, 3)" /> </ p> Description: The use of the code is to intercept the value of the NAME element, from the first letter to the first Three. Sum () function: sum find.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-55067.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="55067" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.034</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = '2UbS3AjT3QOFOOQbOLNUhDywotRwtSXkI6FUsI4LKWV_2BdGapIUuJzI33MYILVkM38g3_2BasbsyBLokedmS1GAGg_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>