<Document1>
<DocumentRequest Application="Standard">
<Doc Format="Pdf">
<Variable Name="CUST" Value = "Aman" Type="String/>
<Variable Name="DPID" Value = "7488493" Type="String/>
<Variable Name="NA Number" Value = "Aman" Type="String/>
<Variable Name="DELTA" Value = "Test" Type="String/>
</Doc>
</DocumentRequest>
</Document1>
这是我的XML,我想从变量标签中获得Name属性的值,并将其分配给不同的变量。输出应该像-
{
"var1":"Aman",
"var2":"7488493",
"var3":"Aman",
"var4":"Test",
}
我想写XSLT来做这个。如何编写XSLT并分配这些值?
只要只有一层Variable
,就可以使用下面这个简单的XSLT-1.0样式表:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:strip-space elements="*" />
<xsl:template match="/Document1/DocumentRequest/Doc[@Format='Pdf']">
<xsl:text>{
</xsl:text>
<xsl:for-each select="Variable">
<xsl:value-of select="concat(' "var',position(),'":"',@Value,'"')" />
<xsl:if test="position()!=last()"><xsl:text>,
</xsl:text></xsl:if>
</xsl:for-each>
<xsl:text>
}</xsl:text>
</xsl:template>
</xsl:stylesheet>
输出为
{
"var1":"Aman",
"var2":"7488493",
"var3":"Aman",
"var4":"Test"
}
上面的代码匹配指定的Doc
元素,然后遍历所有Variable
元素。因为样式表是XSLT 1.0版本,所以它应该可以在Java的XSLT处理器中运行,而不会有更多的复杂性。
我添加了一个xsl-if
子句来省略最后一个元素后面的逗号,使其更像JSON。