apache-camelmarshallingunmarshallingspring-dsl

Transformation From One XML to Another XML Format Using JAXB in Apache Camel Route without using XSLT


I have request xml which is consumed by target system. Target system accpets XML but format is different.So I need to build marshal and unmarshal logic to get data flowing in my route to Target System. So is there any way where I can achive using Java bean approach or jAXB without using dozer or XSLT

Apache Camel with Springboot


Solution

  • Here is a very quick and simple way to do an XSLT transformation.

    Assuming your source data looks like this:

    <?xml version="1.0"?>
    <root>
      <elem1 id="1">
        <child1>Hello</child1>
        <child2>World</child2>
      </elem1>
    </root>
    

    you can have a transform XSLT file that looks a bit like:

    <?xml version="1.0"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
      <xsl:output method="xml" indent="yes" />
      <xsl:template match="elem1">
        <div>
          <h1>Section <xsl:value-of select="@id" /></h1>
          <p><xsl:value-of select="child1" /></p>
          <p><xsl:value-of select="child2" /></p>
        </div>
      </xsl:template>
      <xsl:template match="@*|node()"> <!-- identity transform -->
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates select="node()"/>
        </xsl:copy>
      </xsl:template>
    </xsl:stylesheet>
    

    so you then pass this via the camel xslt transform, one way or another, for example

    from("direct:start")
      .to("xslt:myTransformFile.xsl&saxon=true")
      .to("direct:end")
    

    you should then end up with the following XML message being passed to direct:end:

    <?xml version="1.0"?>
    <root>
      <div>
        <h1>Section 1</h1>
        <p>Hello</p>
        <p>World</p>
      </div>
    </root>
    

    because the identity template has copied any elements that are not matched by another template, and the template replaces any element that match the selection criteria, with the contents of the template. In this case elem1 is replaced, by the contents of the template. The <xsl:value-of ... /> elements are interpreted but any element that doesn't begin <xsl:... is just part of the output.

    For a simple introduction to XSLT, you can look here: https://www.w3schools.com/xml/xsl_intro.asp.