我正在尝试使用for-each
转换JSON对象,但没有任何根元素。这是我的对象,节点号可以更多。
[
{
"id": "1",
"href": "string",
"description": "string",
"isBundle": true,
"isCustomerVisible": true,
"name": "string",
"productSerialNumber": "string",
"productNumber": "string",
"startDate": "2018-11-27T13:26:22.783Z",
"endDate": "2018-11-27T13:26:22.783Z",
"status": "created"
},
{
"id": "2",
"href": "string",
"description": "string",
"isBundle": true,
"isCustomerVisible": true,
"name": "string",
"productSerialNumber": "string",
"productNumber": "string",
"startDate": "2018-11-27T13:26:22.783Z",
"endDate": "2018-11-27T13:26:22.783Z",
"status": "created"
},
{
"id": "3",
"href": "string",
"description": "string",
"isBundle": true,
"isCustomerVisible": true,
"name": "string",
"productSerialNumber": "string",
"productNumber": "string",
"startDate": "2018-11-27T13:26:22.783Z",
"endDate": "2018-11-27T13:26:22.783Z",
"status": "created"
}
]
我正在尝试使用xsl转换:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:template match="/">
<jsonObject xmlns:json="http://json.org/">
<requestResponse>
<xsl:choose>
<xsl:when test="count(//id) > 0">
<returnCode>100</returnCode>
<returnMessage>SUCCESS</returnMessage>
</xsl:when>
<xsl:otherwise>
<returnCode>9999</returnCode>
<returnMessage>BUSINESS_FAULT</returnMessage>
</xsl:otherwise>
</xsl:choose>
</requestResponse>
<xsl:for-each select="@*|node()">
<xsl:if test="id">
<id>
<xsl:value-of select="/id" />
</id>
</xsl:if>
</xsl:for-each>
</jsonObject>
</xsl:template>
</xsl:stylesheet>
如果我有对象的根名称,则可以处理它,但是在这里我需要一些帮助。预先感谢您的任何想法!
答案 0 :(得分:4)
在无根名称数组json中,可以在xslt下面使用<id>
标签。关键点是<jsonArray><jsonElement></jsonElement></jsonArray>
方法。但是您需要注意<jsonElement>
,它应该放在<xsl:for-each select="//jsonArray/jsonElement">
块中。为了不暴露每种症候群,您不应为其中的字段编写根元素。例如<xsl:if test="id">
。
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:fn="http://www.w3.org/2005/xpath-functions"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="http://www.qas.com/OnDemand-2011-03"
xmlns:json="http://json.org">
<xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:template match="/">
<jsonArray>
<xsl:for-each select="//jsonArray/jsonElement">
<jsonElement>
<xsl:if test="id">
<id><xsl:value-of select="id" /> </id>
</xsl:if>
</jsonElement>
</xsl:for-each>
</jsonArray>
</xsl:template>
</xsl:stylesheet>