我有下面的JSON文件,我想通过XSLT进行转换。
[
{
"firstName": "John",
"lastName": "Andy",
"age": "15"
},
{
"firstName": "Ann",
"lastName": "Heather",
"age": "13"
}
] 并取得了以下结果:
[
{
"firstName": "John",
"lastName": "Andy"
},
{
"firstName": "Ann",
"lastName": "Heather"
}
]我所做的是将JSON转换为XML,然后使用以下代码操作该文件:
<xsl:param name="json" as="xs:string">
<xsl:template match="/*" name="xsl:initial-template">
<xsl:variable name="input-as-xml" select="json-to-xml($json)"/>
<xsl:variable name="transformed-xml" as="element(array)">
<array xmlns="http://www.w3.org/2005/xpath-functions">
<xsl:for-each select="/node()">
<map xmlns="http://www.w3.org/2005/xpath-functions">
<string key="firstName">
<xsl:value-of select="$input-as-xml//string[@key='firstName']"/>
</string>
<string key="lastName">
<xsl:value-of select="$input-as-xml//string[@key='lastName']"/>
</string>
</map>
</xsl:for-each>
</array>
</xsl:variable>
<xsl:value-of select="xml-to-json($transformed-xml)"/>
</xsl:template>我使用上述代码的输出是:
[
{
"firstName": "John Ann John Ann",
"lastName": "Andy Heather Andy Heather"
}
]我需要一些帮助来改变我的代码来检索我所需要的信息。
发布于 2019-06-06 11:04:18
我强烈建议您坚持前面问题的答案中所建议的方法,即通过模板将json-to-xml结果推送出去,这样您只需要一个空模板就可以删除age。
<?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"
xpath-default-namespace="http://www.w3.org/2005/xpath-functions"
xmlns="http://www.w3.org/2005/xpath-functions"
exclude-result-prefixes="#all"
version="3.0">
<xsl:param name="json" as="xs:string">
[
{
"firstName": "John",
"lastName": "Andy",
"age": "15"
},
{
"firstName": "Ann",
"lastName": "Heather",
"age": "13"
}
]
</xsl:param>
<xsl:output method="text"/>
<xsl:template match="/" name="xsl:initial-template">
<xsl:variable name="transformed-json-xml">
<xsl:apply-templates select="json-to-xml($json)/node()"/>
</xsl:variable>
<xsl:value-of select="xml-to-json($transformed-json-xml, map { 'indent' : true() })"/>
</xsl:template>
<xsl:mode on-no-match="shallow-copy"/>
<xsl:template match="string[@key = 'age']"/>
</xsl:stylesheet>发布于 2019-06-06 10:42:49
您的xsl:for-each没有正确设置上下文。我想你可能想:
<xsl:for-each select="$input-as-xml/*/*">
<map xmlns="http://www.w3.org/2005/xpath-functions">
<string key="firstName">
<xsl:value-of select="string[@key='firstName']"/>
</string>
<string key="lastName">
<xsl:value-of select="string[@key='lastName']"/>
</string>
</map>
</xsl:for-each>但我认为您可以使用xsl:copy简化它:
<xsl:for-each select="$input-as-xml/*/*">
<map xmlns="http://www.w3.org/2005/xpath-functions">
<xsl:copy-of select="*[@key=('firstName', 'lastName')]"/>
</map>
</xsl:for-each>https://stackoverflow.com/questions/56475491
复制相似问题