【发布时间】:2015-07-18 07:00:05
【问题描述】:
我有一个由 XSLT 处理的 XML,但 Mozilla Firefox 24 ESR 正确解析我的 XML,而 Google Chrome 42 无法从 XML 获取节点。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script>
var xslInput = "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\"> <xsl:output method=\"xml\"/> <xsl:variable name=\"outcome\" select=\"F1- RetBOMs/selectBOM/results[2]/bom\"/><xsl:variable name=\"SINGLE_QUOTE\" select=\""'"\"/> <xsl:template match=\"/*\"> <result> <xsl:copy-of select=\"$outcome\"/> </result></xsl:template> </xsl:stylesheet>" ;
var xmlInput = "<root><F1-RetBOMs><selectBOM><results><bom>Value 1 for first block</bom><description>Description 1 for first block</description></results> <results><bom>Value 2 for second block</bom><description>Description 2 for second block</description></results><rowCount>2</rowCount></selectBOM></F1- RetBOMs></root>";
function createXMLDoc(xmlText){
var parser = new DOMParser();
if (xmlText) {
xmlDoc = parser.parseFromString(xmlText, 'text/xml');
} else {
xmlDoc = document.implementation.createDocument('', '', null);
}
return xmlDoc;
}
function convertXSL(){
var xmldoc = createXMLDoc(xmlInput);
var xsldoc = createXMLDoc(xslInput);
var oProcessor = new XSLTProcessor();
oProcessor.importStylesheet(xsldoc);
try{
var outputDoc = oProcessor.transformToDocument(xmldoc.documentElement, document);
}catch(e){
//console.log(e);
}
document.getElementById('result').innerHTML = new XMLSerializer().serializeToString(outputDoc);
}
</script>
</head>
<title></title>
<body>
<div id="result" style="min-height:300px; min-width: 400px; border: 1px solid blue"></div>
<span id="clickme" style="min-height:30px; min-width: 40px; border: 1px solid red" onclick="convertXSL()">Click Me</span>
</body>
</html>
我试图通过 XSLT 逻辑从xmlInput 获取<bom>Value 1 for first block</bom>,但是当我使用时
<xsl:copy-of select=\"$outcome\"/>
要获取outcome 变量,Chrome 没有通过results 标记进行解析,并在我的结果div 中给出了一个空标记。 Safari 也会发生同样的事情。
您可以在 HTML 文件中尝试整个代码并查看不同的浏览器行为。
谁能告诉我,我做错了什么?这与某些 webkit 行为有关吗?
【问题讨论】:
-
你想达到什么目的?整个代码很奇怪,例如
transformToDocument接受一个参数而不是两个参数,所以我想知道你想用oProcessor.transformToDocument(xmldoc.documentElement, document)实现什么。 -
我可以告诉你当the fixes I identify 被创建并且文件被加载到浏览器中时会发生什么:一个空的蓝色框和一个“点击我”红色框出现。单击“单击我”将“第二个块的值 2”添加到蓝色框中。有粗糙的边缘,但它似乎是典型的基本探索/原型设计。
-
空格不是问题,它们是通过在此处粘贴代码引入的。根本原因是“root”,因为 xpath 依赖于未定义的上下文。将 root 添加到 xpath 可以解决此问题。非常感谢 cmets。
标签: xml google-chrome xslt xml-parsing webkit