简体   繁体   English

在 iframe 中将 XML 文件显示为 HTML(使用 XSLT)

[英]Display an XML file as HTML(using XSLT) in iframe

I have a xml file which I receive as a string from the server.我有一个 xml 文件,我从服务器接收到它作为字符串。 I have my own custom XSLT stylesheet which I want to add it to the XML file dynamically.我有自己的自定义 XSLT 样式表,我想将其动态添加到 XML 文件中。 I have a table which has list of xml files so when I click on one of the files, I want to parse the XML string and embed the stylesheet.我有一个表,其中包含 xml 文件列表,因此当我单击其中一个文件时,我想解析 XML 字符串并嵌入样式表。 The issue is when I parse the xml string I get something like this:问题是当我解析 xml 字符串时,我得到如下信息:

<book>
 <title>test<title>
</book>

with book being the root node. book 是根节点。 What I was expecting was:我所期待的是:

<?xml version="1.0" encoding="UTF-8"?>
<book>
 <title>test<title>
</book>

with xml being the root element which then I can access and insert the stylesheet after that. xml 是根元素,之后我可以访问并插入样式表。 But since it's not the root element and I am not able to add the XSLT stylesheet.但由于它不是根元素,我无法添加 XSLT 样式表。 Here's what I have tried这是我尝试过的

 const parser = new DOMParser();
 const xmlDoc = parser.parseFromString(xmlString, 'application/xml');
 const result =  xmlDoc.createProcessingInstruction('xml-stylesheet', 'href="test.xsl" type="text/xsl"')
 xmlDoc.documentElement.insertAfter(result, xmlDoc.documentElement) // this fails because xml is not the root element

Any help is appreciated.任何帮助表示赞赏。 Also, if there is an alternative way to handle this problem i'd like that too.此外,如果有另一种方法来处理这个问题,我也会喜欢。

As for the DOM manipulation, I think you want至于 DOM 操作,我想你想要

xmlDoc.insertBefore(result, xmlDoc.documentElement);

I don't think it will help applying the XSLT, however.但是,我认为这对应用 XSLT 没有帮助。

As for the code not working, the following should do:至于代码不起作用,应该执行以下操作:

 const xmlString = `<book> <title>test<\/title> </book>`; const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, 'application/xml'); const result = xmlDoc.createProcessingInstruction('xml-stylesheet', 'href="test.xsl" type="text/xsl"'); xmlDoc.insertBefore(result, xmlDoc.documentElement); console.log(new XMLSerializer().serializeToString(xmlDoc)); console.log(xmlDoc);

To process XSLT and write the result to an iframe it might work to use eg要处理 XSLT 并将结果写入 iframe 它可能使用例如

const xmlString = `<book>
 <title>test<\/title>
</book>`;

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'application/xml');

const xslt = `xslt code goes here`;

const xsltDoc = parser.parseFromString(xsltString, 'application/xml');

const xsltProcessor = new XSLTProcessor();

xsltProcessor.importStylesheet(xsltDoc);

const resultDoc = xsltProcessor.transformToDocument(xmlDoc);

const iframeDoc = window.frames.frameName.document;

iframeDoc.open();
iframeDoc.write(new XMLSerializer().serializeToString(resultDoc));
iframeDoc.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM