【问题标题】:Testing nodes against literal double quote in XSLT针对 XSLT 中的文字双引号测试节点
【发布时间】:2021-06-26 17:43:06
【问题描述】:

我有一个看起来像这样的源 XML:

<root>
    <item>a</item>
    <item>b</item>
    <item>"</item>
</root>

我正在尝试将其转换为大致如下所示的 JSON 对象:

{"elements": [
    {"value": "a"},
    {"value": "b"},
    {"value": "\""}
]}

我几乎可以使用大致如下的XSLT 文件:

<xsl:template match="root">
    <xsl:text>{"elements":[</xsl:text>
        <xsl:apply-templates select="item"/>
    <xsl:text>]}</xsl:text>
</xsl:template>

<xsl:template match="item">
    <xsl:text>{</xsl:text>
        <xsl:text>"value":"</xsl:text>
            <xsl:choose>
                <xsl:when test="current()=&quot;]">
                    <xsl:text>\"</xsl:text>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="current()"/>
                </xsl:otherwise>
            </xsl:choose>
        <xsl:text>"</xsl:text>
    <xsl:text>}</xsl:text>
    <xsl:if test="position() != last()">
        <xsl:text>,</xsl:text>
    </xsl:if>
</xsl:template>

问题是当我运行它时,我得到以下回溯:

Traceback (most recent call last):
  File "run_test.py", line 26, in <module>
    single_test("test.xml", "test.xslt")
  File "run_test.py", line 7, in single_test
    transform = etree.XSLT(xslt_doc)
  File "src/lxml/xslt.pxi", line 410, in lxml.etree.XSLT.__init__
lxml.etree.XSLTParseError: xsl:when : could not compile test expression 'current()="]'

现在我尝试以几种不同的方式访问当前节点的文本值,其中许多在初始写入时成功,但我没有设法将其合并到我的测试中。这是我尝试过的:

  • 将文本保存在变量中,将测试替换为"$var=&amp;quot;"
  • current() 替换为text()current()/@text
  • self::node()[text()=&amp;quot;]替换当前

所有这些都给了我同样的错误,这告诉我我在这里一定是误解了。有关如何进行此比较的任何建议?首选 XSLT 1.0。

【问题讨论】:

    标签: json xml xslt escaping double-quotes


    【解决方案1】:

    XPath 表达式中的文字字符串必须加引号。而不是:

    <xsl:when test="current()=&quot;]">
    

    (也有一个多余的右括号)使用:

    <xsl:when test="current()='&quot;'">
    

    或很快:

    <xsl:when test=".='&quot;'">
    

    【讨论】:

    • 奇迹,我可以发誓我尝试过,但可能与其他一些没有意义的事情结合在一起。
    • 只需要等待时间限制:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多