XSLT - 在REST响应结果转换XML
问题描述:
目前我正在尝试使用XSLT一些XML伪代码转换为休息响应结果XSLT - 在REST响应结果转换XML
例如,下面的XML:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:functions="http://foo.com/api/rest">
<item bar="foo">some item</item>
<functions:fetch a="3" b="foo" />
</root>
而且如果http://foo.com/services/rest/fetch/a/3/b/foo
结果是:
<?xml version="1.0" encoding="UTF-8"?>
<rsp stat="ok">
<book>
<title>Ethics</title>
</book>
<book>
<title>Beyond Good and Evil</title>
</book>
</rsp>
的XSLT解析我试图得到的结果是:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:functions="http://foo.com/api/rest">
<item bar="foo">some item</item>
<book>
<title>Ethics</title>
</book>
<book>
<title>Beyond Good and Evil</title>
</book>
</root>
我知道我可以使用<xsl:value-of select="document('http://foo.com/services/rest/fetch/a/3/b/foo')"/>
来提出请求,但我坚持如何在同一个XSLT中生成和处理它。
任何帮助将不胜感激,提前致谢!
答
这里是一个可能的纯XSLT 1.0解决方案:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:functions="http://foo.com/api/rest"
exclude-result-prefixes="functions">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="vDynPart">
<xsl:for-each select="/*/functions:*/@*">
<xsl:value-of select="concat('/', name(), '/', .)"/>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="vRes" select=
"document(concat('http://foo.com/services/rest/fetch',
$vDynPart)
)"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
<xsl:apply-templates select="$vRes/*/node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="functions:*"/>
</xsl:stylesheet>
答
感谢来自Dimitre答案,我找到了解决办法!
(我提出一个新的回复,因为我调整Dimitre解决一点与任何函数名,并在同一个XML多种功能工作)
这里XSLT:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:functions="http://foo.com/api/rest"
exclude-result-prefixes="functions">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="functions:*">
<xsl:variable name="request_function">
<xsl:value-of select="local-name(.)"/>
</xsl:variable>
<xsl:variable name="request_parameters">
<xsl:for-each select="@*">
<xsl:value-of select="concat('/', name(), '/', .)"/>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="rest_response" select="document(concat('http://foo.com/services/rest/', $request_function, $request_parameters))"/>
<xsl:apply-templates select="$rest_response/*/node()"/>
</xsl:template>
</xsl:stylesheet>
谢谢!