How to change an entire element with an existing value using xslt?

I have an original file with a header that I want to change for another (saved in another file):

original file:

<doc1>
    <header>
        <a>aaaa</a>
        <b>bbbb</b>
    </header>
    <content>
      <z>zzzzzzzzzzzzz</z>
    </content>
</doc1>

new header (in file):

<header>
    <c>cccc</c>
</header>

Expected Result:

    <doc1>
    <header>
        <c>cccc</c>
    </header>
    <content>
      <z>zzzzzzzzzzzzz</z>
    </content>
</doc1>

Thanks in advance!

+3
source share
2 answers

This is a conversion (for demonstration purposes, a new header is inserted into the XSLT stylesheet):

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my">
 <xsl:output omit-xml-declaration="yes"/>

 <my:header>
   <header>
    <c>cccc</c>
   </header>
 </my:header>

 <xsl:variable name="vHeaderDoc" select="document('')/*/my:header"/>
    <xsl:template match="node()|@*">
      <xsl:copy>
         <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>

    <xsl:template match="header">
     <xsl:copy-of select="$vHeaderDoc/*"/>
    </xsl:template>
</xsl:stylesheet>

when applied to the provided XML document :

<doc1>
    <header>
        <a>aaaa</a>
        <b>bbbb</b>
    </header>
    <content>
        <z>zzzzzzzzzzzzz</z>
    </content>
</doc1>

creates the desired, correct result :

<doc1>
    <header xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my">
    <c>cccc</c>
   </header>
    <content>
        <z>zzzzzzzzzzzzz</z>
    </content>
</doc1>

In the real case, you will have :

 <xsl:variable name="vHeaderDoc" select="document('Header.xml')"/>

header 'Header.xml', , XSLT ( , URL- ).

header xsl: node.

. XSLT document().

+1

Source: https://habr.com/ru/post/1785941/


All Articles