javascript - javascript transformToDocument XSLT 不是预期的输出
问题描述
我正在尝试使用下面的代码直接通过浏览器(Chrome)执行 xsl 转换。
目标是使用 XML 作为数据库,可用于通过使用 xsl(和良好的 html 输出)提取信息,但似乎有些问题。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"/>
<script>
function displayResult()
{
var text_xml = "<div id='example'><div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div><div>7</div><div>8</div><div>9</div><div>VALOR</div></div>";
parser = new DOMParser();
xml = parser.parseFromString(text_xml,"text/xml");
var text_xls="<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:template match='/'><xsl:for-each select='(./div/div[(. = 'VALOR')])'><div><xsl:value-of select='.'/></div></xsl:for-each></xsl:template></xsl:stylesheet>";
parser2 = new DOMParser();
xlsDoc = parser2.parseFromString(text_xls,"text/xml");
{
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xlsDoc);
xml = xsltProcessor.transformToDocument(xml, document);
}
xml = parser.parseFromString(text_xml,"text/xml");
S3L = xml;
document.getElementById("CR_tab").innerHTML=S3L.documentElement.outerHTML;
}
</script>
</head>
<body onload="displayResult()">
<div id="CR_id" class="w3-container my_tab">
<h2>Result</h2>
<div id="CR_tab">
</div>
</div>
</body>
</html>
代码运行正常,但结果未按预期出现:预期结果:
Result
1
The result I'm getting:
Result
1
2
3
4
5
6
7
8
9
VALOR
我用一些 xsl 处理器测试过,结果很好,但 Chrome 处理器不行
很感谢任何形式的帮助。
解决方案
以下代码 JavaScript 代码,使用来自另一个答案的 XSLT,似乎在 Chrome 中工作,只给出值1
:
var text_xml = "<div id='example'><div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div><div>7</div><div>8</div><div>9</div><div>VALOR</div></div>";
const xsl = `<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='/'>
Result:
<xsl:value-of select='div/div[1]'/>
<\/xsl:template>
<\/xsl:stylesheet>`;
const domParser = new DOMParser();
const doc = domParser.parseFromString(text_xml, 'application/xml');
const xsltDoc = domParser.parseFromString(xsl, 'application/xml');
const processor = new XSLTProcessor();
processor.importStylesheet(xsltDoc);
const resultFrag = processor.transformToFragment(doc, document);
console.log(resultFrag);
document.querySelector('#output').appendChild(resultFrag);
<h1>Test</h1>
<div id=output></div>
推荐阅读
- python - 并非所有 HTML 似乎都使用 BeautifulSoup 检索
- android - 无法在颤动中切换到测试版通道
- java - 更改要在 Java 中的单元测试中使用的方法的行为
- asp.net - 为什么用户需要键入的行出现错误?在 asp.net aspx mvc 中
- sql - postgres:在插入之前删除需要锁定?
- c++ - 为什么 gcc 和 clang 会为 std::find 生成这么多代码?
- python - 熊猫 - 取同一年的平均值,但年份分为季度
- node.js - Node TypeError - require()'d 类方法上的“不是函数”
- ruby - 如何在 Ruby 中创建多模块项目(子项目)
- python - 用户有没有办法为所有使用它的函数全局覆盖关键字参数的默认值?