如何使用XSLT从xml到json获取值

问题描述 投票:1回答:1

我有一个问题,我尝试使用XSLT将XML转换为JSON。就名字而言,我得到了所有,但价值观却是另一回事。

<datapost>
<fields>
    <field>
        <id>emailId</id>
        <name>emailName</name>
        <values>
            <value>[email protected]</value>
        </values>
    </field>
</fields>

此刻,我只得到正确的“名称”,但是“值”(emailIdName&emailId&[email protected])是我显然不想要的所有值。

{
    "emailName":{
        "[email protected]"
    }
}

我只想获取值中的“名称”和“值”([email protected])这就是我想要得到的结果:

    {
    "emailName":{
        "[email protected]"
    }
}

我这样做是为了遍历多个子元素和孙元素:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="xml" indent="no" encoding="UTF-16" omit-xml-declaration="yes"/>
	<xsl:template match="/">
		<body>{
        
			<xsl:call-template name="fieldsName"></xsl:call-template>
			<xsl:text>&#13;&#10;</xsl:text>
		</body>
	</xsl:template>
	<xsl:template name="fieldsName">
		<xsl:for-each select="//datapost[position()=1]/fields/field">
        "
			<xsl:value-of select="name"/>" : 
			<xsl:call-template name="fieldsValue"/>}
      
		</xsl:for-each>
	</xsl:template>
	<!-- Array Element -->
	<xsl:template match="*" mode="ArrayElement">
		<xsl:call-template name="fieldsValue"/>
	</xsl:template>
	<!-- Object Properties -->
	<xsl:template name="fieldsValue">
		<xsl:variable name="childName" select="//datapost[position()=1]/fields/field/values/value"/>
		<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>
</xsl:stylesheet>
json xml xslt
1个回答
0
投票
XML中的元素名称选择不当,这可能使您感到困惑(这肯定使我感到困惑)。人们可能希望“字段”包含一个字段,但实际上包含所有字段。所以改变
© www.soinside.com 2019 - 2024. All rights reserved.