我需要将 XML 源转换为指定的 JSON 格式。为此,我需要删除标头节点,保留数组主体并封装在 [] 中。我已经转换了正文,但我无法删除标题节点并插入封装 []
这是我收到的 XML 格式:
<?xml version="1.0" encoding="UTF-8"?>
<ns1:DDMRP_Parts xmlns:ns1="urn:za.sabmiller.com:supplychain:3rdp:transdata">
<Part>
<PartNumber>000096</PartNumber>
<Location>A000</Location>
<Description>TEST OF RAMIS</Description>
<UnitOfMeasure>EA</UnitOfMeasure>
<PartType>1</PartType>
<FixedLeadTime>1</FixedLeadTime>
<MaterialType>Filling & Mixing Eq</MaterialType>
</Part>
<Part>
<PartNumber>000096</PartNumber>
<Location>A000</Location>
<Description>TEST OF RAMIS</Description>
<UnitOfMeasure>EA</UnitOfMeasure>
<PartType>1</PartType>
<FixedLeadTime>1</FixedLeadTime>
<MaterialType>Filling & Mixing Eq</MaterialType>
</Part>
</ns1:DDMRP_Parts>
我曾尝试使用 SAP PI 上提供的适配器进行转换,但这并不适合完整的数组主体。我曾尝试使用 XSLT 重新格式化,但删除外部节点并用 [ ] 封装并不正确
这是我的 XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">{
<xsl:apply-templates select="*"/>}
</xsl:template>
<!-- Object or Element Property-->
<xsl:template match="*">
"<xsl:value-of select="name()"/>" : <xsl:call-template name="Properties"/>
</xsl:template>
<!-- Array Element -->
<xsl:template match="*" mode="ArrayElement">
<xsl:call-template name="Properties"/>
</xsl:template>
<!-- Object Properties -->
<xsl:template name="Properties">
<xsl:variable name="childName" select="name(*[1])"/>
<xsl:choose>
<xsl:when test="not(*|@*)">"<xsl:value-of select="."/>"</xsl:when>
<xsl:when test="count(*[name()=$childName]) > 1">{ "<xsl:value-of select="$childName"/>" :[<xsl:apply-templates select="*" mode="ArrayElement"/>] }</xsl:when>
<xsl:otherwise>{
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="*"/>
}</xsl:otherwise>
</xsl:choose>
<xsl:if test="following-sibling::*">,</xsl:if>
</xsl:template>
<!-- Attribute Property -->
<xsl:template match="@*">"<xsl:value-of select="name()"/>" : "<xsl:value-of select="."/>",
</xsl:template>
这是我目前正在生产的:
{
"ns1:DDMRP_Parts" : { "Part" :[{
"PartNumber" : "000096",
"Location" : "A000",
"Description" : "TEST OF RAMIS",
"UnitOfMeasure" : "EA",
"PartType" : "1",
"FixedLeadTime" : "1",
"MaterialType" : "Filling & Mixing Eq"
},{
"PartNumber" : "000096",
"Location" : "A000",
"Description" : "TEST OF RAMIS",
"UnitOfMeasure" : "EA",
"PartType" : "1",
"FixedLeadTime" : "1",
"MaterialType" : "Filling & Mixing Eq"
}] }}
这是我需要输出的:
[{
"PartNumber" : "000096",
"Location" : "A000",
"Description" : "TEST OF RAMIS",
"UnitOfMeasure" : "EA",
"PartType" : "1",
"FixedLeadTime" : "1",
"MaterialType" : "Filling & Mixing Eq"
},{
"PartNumber" : "000096",
"Location" : "A000",
"Description" : "TEST OF RAMIS",
"UnitOfMeasure" : "EA",
"PartType" : "1",
"FixedLeadTime" : "1",
"MaterialType" : "Filling & Mixing Eq"
}]