问题描述
|
我有一个XML,看起来像这样
<person>
<name>
<name-first>foo</name-first>
<name-last>bar</name-last>
</name>
<age>20</age>
<city>Nowhere</city>
</person>
我想将其转换为
person:
{
name: {
name-first:\'foo\',name-last:\'bar\'
},age:\'20\',city:\'Nowhere\'
}
提前致谢。
解决方法
这是一个简单的转换-首先:
<xsl:stylesheet version=\"1.0\"
xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">
<xsl:output method=\"text\"/>
<xsl:strip-space elements=\"*\"/>
<xsl:param name=\"pIndents\" select=\"\' \'\"/>
<xsl:template match=\"*[*]\">
<xsl:param name=\"pcurrentIndents\" select=\"\'\'\"/>
<xsl:value-of select=\"concat($pcurrentIndents,name(),\':\')\"/>
<xsl:value-of select=\"concat(\'
\',$pcurrentIndents,\'{\')\"/>
<xsl:apply-templates>
<xsl:with-param name=\"pcurrentIndents\" select=
\"concat($pcurrentIndents,$pIndents)\"/>
</xsl:apply-templates>
<xsl:value-of select=\"concat(\'
\',\'}\')\"/>
</xsl:template>
<xsl:template match=\"*[not(*)]\">
<xsl:param name=\"pcurrentIndents\" select=\"\'\'\"/>
<xsl:text>
</xsl:text>
<xsl:value-of select=\"concat($pcurrentIndents,\':\')\"/>
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
当此转换应用于提供的XML文档时:
<person>
<name>
<name-first>foo</name-first>
<name-last>bar</name-last>
</name>
<age>20</age>
<city>nowhere</city>
</person>
所需的正确结果产生了:
person:
{ name:
{
name-first:foo
name-last:bar
}
age:20
city:nowhere
}
说明:
有两个匹配元素的模板。
匹配“ 5”的模板匹配具有子元素的元素。它使用name()
函数生成当前匹配元素的名称,然后是:
字符,NL字符,当前缩进(空格数),最后是{
字符。然后使用templates9ѭ参数将模板应用于当前匹配元素的子节点,该参数传递当前缩进以预定的空格字符增量增加(如全局参数$pIndents
所指定)。最后,在新行上使用当前缩进,右花括号是putput。
匹配*[not(*)]
(没有任何元素作为子元素的元素)的模板相似,但更简单。它输出当前缩进处的匹配元素名称和:
字符。在此处应用模板会为非元素节点调用XSLT内置模板-在这种情况下,将选择与文本节点匹配的内置模板,并将其简单地复制到输出中。
,您想要的是XML到JSON的转换器。
试试这个:http://www.thomasfrank.se/xml_to_json.html
,这是一个xsl模板示例,该模板应该使您了解如何将xml转换为所需的输出:
<xsl:template match=\"person\">
person:
{
name: {
name-first:<xsl:value-of select=\"name/name-first\"/>,name-last:<xsl:value-of select=\"name/name-last\"/>
},age:<xsl:value-of select=\"age\"/>,city:<xsl:value-of select=\"city\"/>
}
</xsl:template>
,有许多通用的XSLT解决方案可用于将XML转换为JSON输出。
例如:
http://code.google.com/p/xml2json-xslt/
http://www.bramstein.com/projects/xsltjson/
我通过xml2json-xslt \的xml2json.xslt
运行了XML,并生成了以下JSON输出:
{
\"person\":
{
\"name\":
{
\"name-first\":\"foo\",\"name-last\":\"bar\"
},\"age\":20,\"city\":\"nowhere\"
}
}