简体   繁体   中英

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? eg:

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM