[英]How to convert xml to string using xslt
我想转换以下 XML
<Root>
<instruction>
<header>
<type>A</type>
<date>29-08-2018</date>
</header>
<message>
<name>parth</name>
<age>24</age>
</message>
</instruction>
</Root>
使用 XSLT 下面的 XML
<Root>
<request>
<instruction>
<header>
<type>A</type>
<date>29-08-2018</date>
</header>
<message>
<name>parth</name>
<age>24</age>
</message>
</instruction>
</request>
</Root>
在上面的输出中, <request>
标签内的所有标签都是字符串的形式,而不是 XML 元素。 有什么建议吗?
考虑到您的问题中显示的内容,我会像这样编写 XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="Root">
<xsl:copy>
<request>
<xsl:apply-templates />
</request>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
这将输出您的问题中所示的 XML。 见http://xsltfiddle.liberty-development.net/pPqsHTL
请注意在复制现有元素时使用标识模板。
但是,从您的评论看来,您想将元素转换为文本,这是通过“转义”它们来实现的。 如果是这种情况,我会像这样编写 XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" cdata-section-elements="request" />
<xsl:template match="*">
<xsl:value-of select="concat('<', name())" />
<xsl:for-each select="@*">
<xsl:value-of select="concat(' ', name(), '="', ., '"')" />
</xsl:for-each>
<xsl:text>></xsl:text>
<xsl:apply-templates />
<xsl:value-of select="concat('</', name(), '>')" />
</xsl:template>
<xsl:template match="Root">
<xsl:copy>
<request>
<xsl:apply-templates />
</request>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
这输出以下
<Root>
<request><![CDATA[
<instruction a="1">
<header>
<type>A</type>
<date>29-08-2018</date>
</header>
<message>
<name>parth</name>
<age>24</age>
</message>
</instruction>
]]></request>
</Root>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.