【发布时间】:2019-05-24 10:33:21
【问题描述】:
我有以下xml
<Request>
<Record>
<ID>123456789</ID>
<OtherID>ABC123</OtherID>
<Title>Example</Title>
<Properties>
<Attribute type="Main">
<Name>Description</Name>
<Value>This is an example</Value>
</Attribute>
<Attribute type="Main">
<Name>Source</Name>
<Value>A1</Value>
</Attribute>
<Attribute type="Main">
<Name>Source</Name>
<Value>B</Value>
</Attribute>
<Attribute type="Main">
<Name>Represenative</Name>
<Value>Mike</Value>
</Attribute>
<Attribute type="Main">
<Name>Animal</Name>
<Value>Elephant</Value>
</Attribute>
</Properties>
</Record>
</Request>
我想要下面的json。
{
"Record":{
"ID":"123456789",
"OtherID":"ABC123",
"Title":"Example",
"Properties":[
{
"Type":"Main",
"Value":"Source",
"Name":"A1"
},
{
"Type":"Main",
"Value":"Source",
"Name":"B"
},
{
"Type":"Main",
"Value":"Representative",
"Name":"Mike"
},
{
"Type":"Main",
"Value":"Animal",
"Name":"Elephant"
}
],
"Description":"This is an example"
}
}
请注意,description 属性不是数组的一部分,它与属性、ID、OtherID 和 Title 处于同一级别。
我正在应用以下 xslt 将 xml 转换为 json。在这个 xml 中,我声明了一个变量,它将包含描述并将添加到对象的末尾
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0">
<xsl:output method="text" />
<xsl:template match="/">
<xsl:variable name="description2" select="''" />
{
<xsl:for-each select="Request/Record">
"Record": {
"ID":"<xsl:value-of select="ID" />",
"OtherId": "<xsl:value-of select="OtherID" />",
"Title":"Example",
<xsl:if test="Properties">
"Properties": [
<xsl:for-each select="Properties/Attribute">
<xsl:if test="soi:Name = 'Description'">
<xsl:variable name="description2" select="<xsl:value-of select="Value" />" />
<xsl:if test="position() != last()">,</xsl:if>
</xsl:if>
<xsl:if test="Name != 'Description'">
{
"Type": "Main",
"Name": "<xsl:value-of select="Name" />",
"Value": "<xsl:value-of select="Value" />"
}
<xsl:if test="position() != last()">,</xsl:if>
</xsl:if>
</xsl:for-each>
]
</xsl:if>
}<xsl:if test="position() != last()">,</xsl:if>
</xsl:for-each>
<xsl:if test="description2!=''">
,"Description":"<xsl:value-of select="$description2"/>"
</xsl:if>
}
</xsl:template>
不幸的是,我得到了这个输出
{
"Request":{
"ID":"123456789",
"OtherID":"ABC123",
"Title":"Example",
"Properties":[
{
"Type":"Main",
"Value":"Source",
"Name":"A1"
},
{
"Type":"Main",
"Value":"Source",
"Name":"B"
},
{
"Type":"Main",
"Value":"Representative",
"Name":"Mike"
},
{
"Type":"Main",
"Value":"Animal",
"Name":"Elephant"
}
],
"Description":""
}
}
description 的值是空的,因为我不知道如何在循环中重新分配变量 description 的值。我使用双循环来获取描述,但效率非常低。
欢迎任何建议
提前致谢。
【问题讨论】:
-
在 XSLT 中,变量的值一旦定义就无法更改。