[英]How to do a xsl-template match for a html string
我有一種情況,我需要使用XSLT在pdf中呈現html。 我在xml文件中有一些html內容,例如
<section>
<p><b><u>Heelo</u></b></p>
</section>
我需要在pdf中進行渲染。
<xsl:template match="b">
<fo:inline font-weight="bold">
<xsl:apply-templates select="*|text()" />
</fo:inline>
</xsl:template>
<xsl:template match="u">
<fo:inline text-decoration="underline">
<xsl:apply-templates select="*|text()" />
</fo:inline>
</xsl:template>
<xsl:template match="i">
<fo:inline font-style="italic">
<xsl:apply-templates select="*|text()" />
</fo:inline>
</xsl:template>
但是此模板匹配不起作用。 如何實現這一目標,或者在Java中創建xml時有什么方法可以替換<as <和> as>?
我在這里先向您的幫助表示感謝 !!!
如果您想解析HTML,則需要一種集成HTML解析器的方法,如果您通過https://github.com/davidcarlisle/web-xslt/在XSLT 2中使用David Carlisle的HTML解析器實現,則可以使用XSLT 2處理器。 blob / master / htmlparse / htmlparse.xsl ,然后可以將其導入並調用該函數以將section
元素的內容解析為要由模板處理的節點:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
xmlns:d="data:,dpc"
exclude-result-prefixes="#all"
version="3.0">
<xsl:import href="https://raw.githubusercontent.com/davidcarlisle/web-xslt/master/htmlparse/htmlparse.xsl"/>
<xsl:output indent="yes"/>
<xsl:template match="/">
<fo:root>
<fo:layout-master-set>
<fo:simple-page-master master-name="first" page-height="29.7cm" page-width="21cm" margin-top="1cm" margin-bottom="2cm" margin-left="2.5cm" margin-right="2.5cm">
<fo:region-body margin-top="1cm"/>
<fo:region-before extent="1cm"/>
<fo:region-after extent="1.5cm"/>
</fo:simple-page-master>
</fo:layout-master-set>
<fo:page-sequence master-reference="first">
<fo:flow flow-name="xsl-region-body">
<fo:block>
<xsl:apply-templates/>
</fo:block>
</fo:flow>
</fo:page-sequence>
</fo:root>
</xsl:template>
<xsl:template match="section">
<fo:block>
<xsl:apply-templates select="d:htmlparse(., '', true())/node()"/>
</fo:block>
</xsl:template>
<xsl:template match="b">
<fo:inline font-weight="bold">
<xsl:apply-templates select="*|text()" />
</fo:inline>
</xsl:template>
<xsl:template match="u">
<fo:inline text-decoration="underline">
<xsl:apply-templates select="*|text()" />
</fo:inline>
</xsl:template>
<xsl:template match="i">
<fo:inline font-style="italic">
<xsl:apply-templates select="*|text()" />
</fo:inline>
</xsl:template>
</xsl:stylesheet>
https://xsltfiddle.liberty-development.net/94hvTAp
我已經按照問題中的說明使用了模板,但請注意,通常可以將<xsl:apply-templates select="*|text()" />
所有用法簡化為<xsl:apply-templates/>
。
其他方式取決於所使用的特定XSLT處理器(即,它是否提供擴展名,例如http://saxonica.com/html/documentation/functions/saxon/parse-html.html,還是它允許您實現自己的擴展功能集成) HTML解析器)。
如果HTML是格式正確的XML(例如,具有所有必要的結束標記和引號屬性,而不使用HTML特定的實體引用),那么您還可以將XPath 3.1函數parse-xml-fragment
與XSLT 3處理器(如Saxon 9.8)一起使用或更高版本:
<xsl:template match="section">
<fo:block>
<xsl:apply-templates select="parse-xml-fragment(.)/node()"/>
</fo:block>
</xsl:template>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.