下面是從Safari和Opera的錯誤消息(IE和Firefox處理XML文件OK,鉻掛斷):
Safari瀏覽器:
This page contains the following errors:
error on line 1 at column 40: Extra content at the end of the document Below is a rendering of the page up to the first error.
This document was created as the result of an XSL transformation. The line and column numbers given are from the transformed result.
歌劇:
This document had an invalid XSLT stylesheet. Error message from the XSLT engine: Error: invalid XML output: unexpected start-tag (root element already specified)
來自Safari的消息特別好 - 它確認問題不在於執行轉換,而是在於生成的結果。
來自Opera的消息不太好,但兩種瀏覽器都談論同樣的事情:他們將轉換的結果不是作爲HTML,而是作爲XML來處理,並報告結果不是一個很好的結果,形成了XML文檔(不是單個頂層元素)。
事實上,轉換生成此輸出:
<?xml version="1.0" encoding="utf-8"?><head><title>Producenter</title></head><body><p>8</p></body>
和XML聲明使瀏覽器期望的XML文檔,才發現這不是一個良好的XML文檔。
解決方案 - :在xsl:stylesheet
指令後立即
<xsl:output method="html"/>
根據分析,修復是輕鬆自然只是添加此。
的完全轉化現在變成:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<head><title>Producenter</title></head>
<body>
<p>
<xsl:value-of select="producers/producer/id"/>
</p>
</body>
</xsl:template>
</xsl:stylesheet>
輸出產生不再以XML聲明開始和內容類型清楚地指定爲text/html
:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Producenter</title>
</head>
<body>
<p>8</p>
</body>
和Safari和Opera都很高興地顯示沒有錯誤信息的結果。
請記住:在生成HTML輸出時,請務必在<xsl:output>
指令中明確指定。
做注意:雖然這個答案揭示了問題的真正原因並提供了一個解決方案,但這並不排除編寫好的和完整的HTML文檔的必要性。因此,它是很好指定html
作爲文件的頂部元素。另一個好處是,如果生成的輸出的頂層元素是html
,則XSLT處理器會自動扣除輸出必須爲「html」並執行html序列化,即使沒有明確指定輸出方法。
按照W3C XSLT 1.0 Specification:
The default for the method attribute is chosen as follows. If
the root node of the result tree has an element child,
the expanded-name of the first element child of the root node (i.e. the document element) of the result tree has local part html (in any
combination of upper and lower case) and a null namespace URI, and
any text nodes preceding the first element child of the root node of the result tree contain only whitespace characters,
then the default output method is html; otherwise, the default output method is xml.
工作對我來說,是真正的文件使用UTF-8編碼? –
你有沒有試過現有的答案?由於您的當前xslt具有多個根元素,因此產生的格式不正確。 –