转换文本(javascript)文件中包含的xml

时间:2012-02-18 01:17:58

标签: xslt xslt-2.0

我有一个javascript文件,如下所示:

if (x > 0 && x < 100) {
    $('#thing').append('<foo id="foo' + x + '">' + stuff + '</foo>');
}

一个xsl样式表,如下所示:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:template match="foo">
        <div>
            <xsl:copy-of select="@*"/>
            <xsl:value-of select="."/>
        </div>
     </xsl:template>
</xsl:stylesheet>

我希望能够将该模板以及可能的其他模板应用于javascript文件中包含的xml。

在这种情况下,输出应如下所示:

if (x > 0 && x < 100) {
    $('#thing').append('<div id="foo' + x + '">' + stuff + '</div>');
}

如果它更容易解析,我将在javascript文件上使用以下约束:

  1. 我永远不会使用&amp;,&lt;,或&gt;在XML标签内部或之间。
  2. 我永远不会使用嵌套的XML标记。
  3. 我只会在XML标记中或周围使用双引号(“)来设置元素属性。
  4. 我将始终围绕每个&lt;或者&gt;文本的常规javascript部分中的字符。
  5. 我可能会根据需要制定其他约束。

    我正在使用Saxon,所以我可以使用XSLT 2.0函数和撒克逊扩展。

1 个答案:

答案 0 :(得分:1)

这似乎有用(你的输入文本在jsxml.txt中):

$ saxon9 -it main jsxml.xsl
if (x > 0 && x < 100) {
    $('#thing').append('<div id="foo' + x + '">' + stuff + '</div>');
}


<xsl:stylesheet version="2.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:dpc="data:,dpc">

<xsl:import href="http://web-xslt.googlecode.com/svn/trunk/htmlparse/htmlparse.xsl"/>

<xsl:output method="text"/>

<xsl:template name="main">
 <xsl:variable name="in" select="unparsed-text('jsxml.txt')"/>
  <xsl:copy-of select="dpc:serialise(dpc:apply-templates(dpc:htmlparse($in,'',false())))"/>
 </xsl:template>


<xsl:function name="dpc:apply-templates">
 <xsl:param name="n"/>
 <xsl:apply-templates select="$n"/>
</xsl:function>

<xsl:function name="dpc:serialise">
 <xsl:param name="n"/>
 <xsl:apply-templates select="$n" mode="verb"/>
</xsl:function>

<xsl:template mode="verb" match="*">
 <xsl:value-of select="concat('&lt;',name())"/>
 <xsl:value-of select="@*/concat(' ',name(),'=&quot;',.,'&quot;')"/>
 <xsl:value-of select="'&gt;'"/>
 <xsl:apply-templates mode="verb"/>
 <xsl:value-of select="concat('&lt;/',name(),'&gt;')"/>
</xsl:template>



<xsl:template match="foo">
 <div>
  <xsl:copy-of select="@*"/>
  <xsl:value-of select="."/>
 </div>
</xsl:template>

</xsl:stylesheet>
相关问题