简体   繁体   English

使用Castor根据属性值解析xml

[英]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: 使用Castor使用映射文件将以下xml解析为POJO非常简单:

<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!). 这个人为设计的示例基于我必须使用的XML(我还没有编写它!)。 Any ideas on how to approach this with Castor mapping files? 关于如何使用Castor映射文件解决此问题的任何想法?

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. 更改Java类结构以使人和狗扩展动物,然后为动物编写映射文件。

Or just use XSLT to transform you data. 或者只是使用XSLT来转换您的数据。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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