首页 > 解决方案 > 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 处理器不行

很感谢任何形式的帮助。

标签: javascriptxmlxsltxpath

解决方案


以下代码 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>


推荐阅读