【发布时间】:2022-01-07 14:45:56
【问题描述】:
我需要将 json 消息转换为 XML。我创建了一个基本的 XSL 转换脚本,但生成的 XML 使用带有 json 值作为“键”属性的“地图”标签。
有没有办法将名称值用作标签,还是我必须编写第二个转换 XSL 才能得到我想要的?
json:
<?xml version="1.0"?>
<data>
{ "Policies":
{
"Policy": {
"PolicyNum": "1234",
"Customer": "Smith"
},
"Policy": {
"PolicyNum": "5678",
"Customer": "Jones"
}
}
}
</data>
xsl:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:math="http://www.w3.org/2005/xpath-functions/math" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs math" version="3.0">
<xsl:output indent="yes" omit-xml-declaration="no" />
<xsl:template match="data">
<xsl:copy-of select="json-to-xml(.)"/>
</xsl:template>
</xsl:stylesheet>
生成的 XML:(使用 https://xslttest.appspot.com/)
<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
<map key="Policies">
<map key="Policy">
<string key="PolicyNum">1234</string>
<string key="Customer">Smith</string>
</map>
<map key="Policy">
<string key="PolicyNum">5678</string>
<string key="Customer">Jones</string>
</map>
</map>
</map>
我需要的 XML:
<Policies>
<Policy>
<PolicyNum>1234</PolicyNum>
<Customer>Smith</Customer>
</Policy>
<Policy>
<PolicyNum>5678</PolicyNum>
<Customer>Jones</Customer>
</Policy>
</Policies>
【问题讨论】:
-
我没有看到 JSON 作为输入,同一对象/映射中的两个同名属性
Policy在 JSON 中是不可能的。 -
我认为
json-to-xml需要第二个参数,以确保检测到重复的密钥,您似乎需要使用json-to-xml(., map { 'duplicates' : 'reject' })。