2

我正在使用 XSLT 处理各种 XML 文件。在一个 XML 中,我发现了一个包装好的 JSON 列表:

<list><![CDATA[[
    {
    "title": "Title 1",
    "value": "Value 1",
    "order": 1
    },
    {
    "title": "Title 2",
    "value": "Value 2",
    "order": 2
    }
]]]>
</list>

我的问题是我需要遍历列表。例如:

<xsl:variable name="listVar">
    <!-- do something with list -->
</xsl:variable>
<xsl:for-each select="$listVar">
    <!-- do something with objects in list e.g. -->
    <xsl:value-of select="title"/>
    <xsl:value-of select="value"/>
</xsl:for-each>

如何用 XSLT 做到这一点?我使用 XSLT 3.0 和 Saxon 引擎,版本 9.8 HE。

考虑的解决方案:

一、使用parse-json功能:

但是由于 XPathException,我无法遍历结果:“子轴的上下文项的必需项类型是节点();提供的值(。)具有项类型数组(函数(*))”或“地图不能雾化”。我发现有些功能可能我应该考虑在内,例如 map:get、map:entry,但到目前为止我还没有在我的案例中使用它们。

2. 上述变换前的附加变换:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="3.0">
    <xsl:output method="xml" encoding="UTF-8" indent="no"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="list">
        <list>
            <xsl:copy-of select="json-to-xml(.)"/>
        </list>
    </xsl:template>
</xsl:stylesheet>

进而:

<xsl:variable name="listVar" select="list/array/map"/>

但它不起作用 - 可能是由于添加了命名空间

<list>
    <array xmlns="http://www.w3.org/2005/xpath-functions">
        <map>
...
4

1 回答 1

1

解析时的 JSON 结构在parse-jsonXSLT/XPath 端为您提供了一映射,处理单个数组项的最直接方法是使用?* 查找运算符,然后您可以使用for-each甚至apply-templates

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    exclude-result-prefixes="xs math"
    version="3.0">

    <xsl:template match="list">
        <xsl:apply-templates select="parse-json(.)?*"/>
    </xsl:template>

    <xsl:template match=".[. instance of map(xs:string, item())]">
        <xsl:value-of select="?title, ?value"/>
    </xsl:template>
</xsl:stylesheet>

在哪里访问您可以再次使用的地图值,?foo如上所示。

至于使用由返回的 XML json-to-xml,它会返回 XPath 函数命名空间中的元素,以便选择它们,就像命名空间中的任何其他元素一样,您需要确保xpath-default-namespace为要处理元素的部分设置命名空间来自该命名空间,或者您可以使用命名空间通配符,例如*:array/*:map.

于 2017-10-27T09:54:32.190 回答