简体   繁体   English

使用XML存储在变量中的Javascript XSLT转换

[英]Javascript XSLT Transformation with XML stored in a variable

I need to transform an XML string using XSLT in Javascript. 我需要在Javascript中使用XSLT转换XML字符串。 While the XSLT is stored in its own file, the XML is part of a bigger XML document, and therefor stored as a string in a variable. 虽然XSLT存储在自己的文件中,但XML是更大的XML文档的一部分,因此将其作为字符串存储在变量中。

My current solution looks as follows: 我目前的解决方案如下:

xslt = document.implementation.createDocument("","",null);
xslt.async = false;
xslt.load('xslfile.xsl');

xml = document.implementation.createDocument("","",null);
// here I need to include the XML as it is in the document

xsltProc.importStylesheet(xslt);
xml_dom = xsltProc.transformToDocument(xml);
output += new XMLSerializer().serializeToString(xml_dom.documentElement);

When I save the content of the variable to a file and include it the way I included the XSLT file, I get the desired output (the transformed XML): 当我将变量的内容保存到文件并按照我包含XSLT文件的方式包含它时,我得到了所需的输出(转换后的XML):

xml = document.implementation.createDocument("","",null);
xml.async = false;
xml.load('xmlinput.xml');

I need a way to include the content of the variable to the xml DOM document...or is there a more elegant way? 我需要一种方法将变量的内容包含在xml DOM文档中......还是有更优雅的方式?

thanks in advance 提前致谢

With Mozilla, Opera, Safari, Chrome and with IE 9 you can do eg 有了Mozilla,Opera,Safari,Chrome和IE 9,你可以做到

var xml = new DOMParser().parseFromString(yourVar, 'application/xml');

to parse the XML markup in the variable yourVar into an XML DOM document. 将变量yourVar的XML标记解析为XML DOM文档。

You can store XML in a variable and use jQuery as normal to traverse it, i tend to do something like this: 您可以将XML存储在变量中并使用jQuery正常遍历它,我倾向于执行以下操作:

window.auditDoc = $.parseXML("<?xml version='1.0' encoding='UTF-8'?><Bundle><Audit></Audit></Bundle>");

If i'm doing allot of work with a single xml file then i also find it useful to put it up in window.auditDoc and always refer to it as that. 如果我正在使用单个xml文件进行大量工作,那么我也发现将它放在window.auditDoc中并始终将其作为参考。

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

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