简体   繁体   English

如何使用 xslt 将 xml 转换为字符串

[英]How to convert xml to string using xslt

I want to convert below XML我想转换以下 XML

<Root>
  <instruction>
    <header>
      <type>A</type>
      <date>29-08-2018</date>
    </header>
    <message>
      <name>parth</name>
      <age>24</age>
    </message>
  </instruction>
</Root>

To below XML using XSLT使用 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>

In above output all the tags inside <request> tag are in form of string, not XML elements.在上面的输出中, <request>标签内的所有标签都是字符串的形式,而不是 XML 元素。 Any advice?有什么建议吗?

Taking what is shown in your question, I would write the XSLT like so:考虑到您的问题中显示的内容,我会像这样编写 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>

This outputs the XML as shown in your question.这将输出您的问题中所示的 XML。 See http://xsltfiddle.liberty-development.net/pPqsHTLhttp://xsltfiddle.liberty-development.net/pPqsHTL

Note the use of the identity template in copying existing elements.请注意在复制现有元素时使用标识模板。

However, from your comments it sounds you want to convert the elements to text, which is achieved by "escaping" them.但是,从您的评论看来,您想将元素转换为文本,这是通过“转义”它们来实现的。 If this is the case, I would write the XSLT like this如果是这种情况,我会像这样编写 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('&lt;', name())" />
    <xsl:for-each select="@*">
      <xsl:value-of select="concat(' ', name(), '=&quot;', ., '&quot;')" />
    </xsl:for-each>
    <xsl:text>&gt;</xsl:text>
    <xsl:apply-templates />
    <xsl:value-of select="concat('&lt;/', name(), '&gt;')" />
  </xsl:template>

  <xsl:template match="Root">
    <xsl:copy>
      <request>
        <xsl:apply-templates />
      </request>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

This outputs the following这输出以下

<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>

See http://xsltfiddle.liberty-development.net/nc4NzQJhttp://xsltfiddle.liberty-development.net/nc4NzQJ

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM