xml – 为什么第一个apply-templates中没有select
我正在尝试理解apply-templates但我不明白为什么我不在这里的apply-templates中写任何select =“nodename”:(我想到My CD集合下面的第一个apply-templates)
输入文档中的片段: <?xml version="1.0" encoding="ISO-8859-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> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year> </cd> <cd> <title>Greatest Hits</title> <artist>Dolly Parton</artist> <country>USA</country> <company>RCA</company> <price>9.90</price> <year>1982</year> </cd> XSLT: <?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="cd"> <p> <xsl:apply-templates select="title"/> <xsl:apply-templates select="artist"/> </p> </xsl:template> <xsl:template match="title"> Title: <span style="color:#ff0000"> <xsl:value-of select="."/></span> <br /> </xsl:template> <xsl:template match="artist"> Artist: <span style="color:#00ff00"> <xsl:value-of select="."/></span> <br /> </xsl:template> </xsl:stylesheet> 取自w3schools教程.它如何理解应该选择哪些模板? 解决方法
如规格:
不使用XPath选择的apply-templates,在编译期间应用处理器构建的XML树视图层次结构后的模板,除非您明确驱动模板(就像您对标题和艺术家所做的那样). 您可能还想想built-in template rules如何工作.这些规则在幕后运行,并允许递归过程在没有成功模式匹配的情况下继续. 因此,如果省略根目录的模板匹配,则无论如何都会执行模板,这要归功于内置规则. 我认为处理顺序应该是这样的: >模板与根匹配,xsl:apply-templates告诉处理器将模板应用于catalog元素(在调用它的位置). 内置规则在幕后运行,您必须始终将您的转换视为由模板组成,以及一些其他隐藏(但正在工作)的模板: <xsl:template match="*|/"> <xsl:apply-templates /> </xsl:template> <xsl:template match="text()|@*"> <xsl:value-of select="."/> </xsl:template> <xsl:template match="processing-instruction()|comment()"/> 在您的特定情况下,上述三个模板中的前一个模板是将模板应用于cd元素的一个模板. 每次编写显式模板时,都会覆盖这些内置模板. 例子 你可以通过替换来获得相同的: <xsl:template match="cd"> <p> <xsl:apply-templates select="title"/> <xsl:apply-templates select="artist"/> </p> </xsl:template> 有: <xsl:template match="country|company|price|year"/> <xsl:template match="cd"> <p> <xsl:apply-templates /> </p> </xsl:template> 关于root,在你的情况下,你也可以通过替换来获得相同的: <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <xsl:apply-templates/> </body> </html> </xsl:template> 同 <xsl:template match="/catalog"> <html> <body> <h2>My CD Collection</h2> <xsl:apply-templates/> </body> </html> </xsl:template> 或者仍然: <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <xsl:apply-templates select="catalog"/> </body> </html> </xsl:template> 或者仍然: <xsl:template match="catalog"> <html> <body> <h2>My CD Collection</h2> <xsl:apply-templates /> </body> </html> </xsl:template> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |