Remy
Remy

Reputation: 12703

XSLT - Override one element with another

I have an XML where I basically just need to copy one element over the other.

<sitecore>
  <phrase path="/content/Bootcamper/Data/Forms/Contact" key="Contact" itemid="{1EDC7BBB-2194-4B0E-A031-F0383F60664D}" fieldid="Name" updated="20170410T131336Z">
    <de-CH>Absenden</de-CH>
    <fr-CH>Submit</fr-CH>
    <en>Submit</en>
  </phrase>
  <phrase path="/content/Bootcamper/Data/Forms/Contact/unknown section/Vorname" key="Vorname" itemid="{9D561751-5B89-4B90-A93F-383A591202DE}" fieldid="Title" updated="20170410T123903Z">
    <de-CH>Vorname</de-CH>
    <en>Firstname</en>
  </phrase>
</sitecore>

What I need is a similar XML, but with the content from <de-CH> inside <fr-CH>. And <en> always removed. If <fr-CH> does not exist, it should be created.

<sitecore>
  <phrase path="/content/Bootcamper/Data/Forms/Contact" key="Contact" itemid="{1EDC7BBB-2194-4B0E-A031-F0383F60664D}" fieldid="Name" updated="20170410T131336Z">
    <de-CH>Absenden</de-CH>
    <fr-CH>Absenden</fr-CH>
  </phrase>
  <phrase path="/content/Bootcamper/Data/Forms/Contact/unknown section/Vorname" key="Vorname" itemid="{9D561751-5B89-4B90-A93F-383A591202DE}" fieldid="Title" updated="20170410T123903Z">
    <de-CH>Vorname</de-CH>
    <fr-CH>Vorname</fr-CH>
  </phrase>
</sitecore>

I managed to copy the <de-CH> and remove the <en> tag. But now I have to copy the <de-CH> into a new (or existing) <fr-CH>.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="utf-8" indent="no"/>
    <xsl:template match="node() | @*">
        <xsl:copy>
            <xsl:apply-templates select="node() | @*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="en|fr-CH"/> <!-- this empty template will remove them -->                  
</xsl:stylesheet>

Upvotes: 1

Views: 935

Answers (1)

Tim C
Tim C

Reputation: 70638

If there is always going to be de-CH node present, one way to do it is have a template matching de-CH which copies it, but also adds the fr-CH node too

Try this XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="utf-8" indent="no"/>

  <xsl:template match="node() | @*">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="en|fr-CH"/>

  <xsl:template match="de-CH">
    <xsl:copy-of select="." />
    <fr-CH>
      <xsl:value-of select="." />
    </fr-CH>
  </xsl:template>
</xsl:stylesheet>

Upvotes: 1

Related Questions