我正在尝试使用XSL转换将转换后的XML数据放入HTML页面。这是我的XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="w3.xsl"?>
<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>
</catalog>
XSL文件的内容:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" />
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
但转换的XML没有HTML属性;它看起来像这样:
它应该是这样的:
这是填充DOM的函数,这是导致问题的原因:
//Load the XML document and XSLT document into XML DOM objects
var xml = document.implementation.createDocument("", "", null);
var xslt = document.implementation.createDocument("", "", null);
//Set the async property on both documents to false so that they both completely load
//before any further processing is attempted.
xml.async = false;
xslt.async = false;
//Load XML and XSLT documents into the XML DOM objects.
xml.load("w3.xml");
xslt.load("w3.xsl");
//Create a new XSLTProcessor object and use its importStylesheet() method to import the XSLT DOM object.
var processor = new XSLTProcessor();
processor.importStylesheet(xslt);
//Transform the XML to a new XML DOM object with the transformToDocument() method of the XSLTProcessor.
var XmlDom = processor.transformToDocument(xml)
//Create a new XMLSerializer and use it to serialize the new XML DOM object to a string.
var s = new XMLSerializer();
var output = s.serializeToString(XmlDom.documentElement);
//The result can then be output to the innerHTML property of any element on the page.
var outputDiv = document.getElementById("xmldata");
outputDiv.innerHTML = output;
答案 0 :(得分:0)
我认为您的“主机”HTML页面必须有一个DOCTYPE,将HTML标识为HTML5。
然后,因为您尝试添加HTML 5中过时的属性(例如 bgcolor (请参阅W3C: HTML5 differences from HTML4),所以它们会被忽略,因此不会添加到DOM中。
尝试使用样式属性 - 根据链接页面中的建议。
tr元素的XSLT将如下所示:
<xsl:template match="/">
...
<tr style="background-color:#9acd32;">
<th>Title</th>
<th>Artist</th>
</tr>
...
</xsl:template>