Search code examples
javaxmlcastor

using Castor to parse xml based on attribute values


Using Castor to parse the following xml into POJOs using a mapping file is fairly straightforward:

<human name="bob"/>
<dog owner="alice"/>

It uses the name of the element to map to the class. But what if an attribute should be used to do the mapping? e.g.:

<animal type="human" name="bob"/>
<animal type="dog" owner="alice"/>

This contrived example is based on XML that I have to consume (tho I didn't author it!). Any ideas on how to approach this with Castor mapping files?


Solution

  • There are two ways to approach this. Change your Java class structure to have human and dog extend animal, and then write a mapping file for Animal.

    Or just use XSLT to transform you data. Something like this might work:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
    <xsl:template match="animal">
      <xsl:text disable-output-escaping="yes"><![CDATA[<]]></xsl:text>
           <xsl:value-of select="@type" /><xsl:text disable-output-escaping="yes"> </xsl:text>name="<xsl:value-of select="@name" />"
      <xsl:text disable-output-escaping="yes"><![CDATA[/>]]></xsl:text>
    </xsl:template>
    </xsl:stylesheet>