json to XML using XSL



我需要将json消息转换为XML。我已经创建了一个基本的XSL转换脚本,但生成的XML使用带有json值的"map"标记作为"key"属性。

有没有一种方法可以将名称值用作标记,或者我必须编写第二个转换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>

与其复制XML映射,不如通过模板将其推送,并使用名称为的@key将该映射转换为元素

<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" 
xmlns:fn="http://www.w3.org/2005/xpath-functions" 
exclude-result-prefixes="xs math" version="3.0">
<xsl:output indent="yes" omit-xml-declaration="no" />
<xsl:template match="data">
<xsl:apply-templates select="json-to-xml(.)"/>
</xsl:template>

<xsl:template match="fn:*[@key]">
<xsl:element name="{@key}">
<xsl:apply-templates />
</xsl:element>
</xsl:template>

<xsl:template match="fn:map">
<xsl:apply-templates/>
</xsl:template>

</xsl:stylesheet>

最新更新