Как преобразовать xml в строку, используя xslt - PullRequest
0 голосов
/ 29 августа 2018

Я хочу конвертировать ниже XML

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

Ниже XML с использованием XSLT

<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. Любой совет?

1 Ответ

0 голосов
/ 29 августа 2018

Если взять то, что показано в вашем вопросе, я бы написал 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('&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>

Это выводит следующее

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

См. http://xsltfiddle.liberty -development.net / nc4NzQJ

...