首页 > 解决方案 > 处理 xslt 中的 Json 文本以进行 Xml 到 html 的转换

问题描述

我正在尝试将 XML 转换为 HTML,并且某些 HTML 元素需要将 JSON 文本保存为从 XML 转换的属性值。但是当转换时,我无法在属性中获得正确的 JSON 输出,请帮助我解决这个困惑,因为 " 这是一个双引号

XML:

<?xml version="1.0" encoding="UTF-8"?>
<main>
    <sub id="1" name="A" owner="XXX">text</sub>
    <sub id="2" name="B" owner="yyy">text</sub>
</main>

XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <p>
    <xsl:for-each select="main/sub">
        <span>
            <xsl:attribute name="json">
                <xsl:text>{"properties" : [ {</xsl:text>
                <xsl:for-each select="./@*">                    
                    <xsl:if test="name() = 'id'"><xsl:text>"id" : "</xsl:text><xsl:value-of select="." /><xsl:text>",</xsl:text></xsl:if>
                    <xsl:if test="name() = 'name'"><xsl:text>"name" : "</xsl:text><xsl:value-of select="." /><xsl:text>",</xsl:text></xsl:if>
                    <xsl:if test="name() = 'owner'"><xsl:text>"owner" : "</xsl:text><xsl:value-of select="." /><xsl:text>"</xsl:text></xsl:if>
                </xsl:for-each>
                <xsl:text>} ] }</xsl:text>
            </xsl:attribute>            
        </span>
    </xsl:for-each>
   </p>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

实际输出:

<html>
   <body>
      <p><span json="{&#34;properties&#34; : [ {&#34;id&#34; : &#34;1&#34;,&#34;name&#34; : &#34;A&#34;,&#34;owner&#34; : &#34;XXX&#34;} ] }"></span><span json="{&#34;properties&#34; : [ {&#34;id&#34; : &#34;2&#34;,&#34;name&#34; : &#34;B&#34;,&#34;owner&#34; : &#34;yyy&#34;} ] }"></span></p>
   </body>
</html>

预期产出

<html>
   <body>
      <p><span json="{"properties" : [ {"id" : "1","name" : "A","owner" : "XXX"} ] }"></span><span json="{"properties" : [ {"id" : "2","name" : "B","owner" : "yyy"} ] }"></span></p>
   </body>
</html>

标签: htmljsonxmlxslt

解决方案


Your expected output is not well-formed HTML and can't be handled by any HTML parser, even if it's very lenient. How is it supposed to tell which of the double-quotation marks in the @json attribute represents the end of the attribute value? So you need to change your expectations for the output.

The actual output, in which the quotation marks have been escaped, should work fine.

Except that it's not actually valid JSON: within an object "{...}" you need keyword-value pairs, not a bare value.


推荐阅读