您可以通过为 Channel 类实现 Converter 来解决此问题。
这里有一个例子。它缺少任何类型的错误检查等,并且被简化为仅具有单个 Atom 的 Channel 类。但你会看到它是如何工作的。
类 Channel 和 Converter
@Root()
@Convert(Channel.ChannelConverter.class) // Specify the Converter
public class Channel
{
@Element
private String title;
@Element
private String link;
@Element
private String description;
@Namespace(reference = "http://www.w3.org/2005/Atom", prefix = "atom")
@Element()
private AtomLink atomLink;
// Ctor's / getter / setter ...
static class ChannelConverter implements Converter<Channel>
{
@Override
public Channel read(InputNode node) throws Exception
{
Channel channel = new Channel();
InputNode child;
// Iterate over all childs an get their values
while( ( child = node.getNext() ) != null )
{
switch(child.getName())
{
case "title":
channel.setTitle(child.getValue());
break;
case "description":
channel.setDescription(child.getValue());
break;
case "link":
/*
* "link" can be either a <link>...</link> or
* a <atom:link>...</atom:link>
*/
if( child.getPrefix().equals("atom") == true )
{
AtomLink atom = new AtomLink();
atom.setHref(child.getAttribute("href").getValue());
atom.setRel(child.getAttribute("rel").getValue());
atom.setType(child.getAttribute("type").getValue());
channel.setAtomLink(atom);
}
else
{
channel.setLink(child.getValue());
}
break;
default:
throw new RuntimeException("Unknown Element found: " + child);
}
}
return channel;
}
@Override
public void write(OutputNode node, Channel value) throws Exception
{
/*
* TODO: Implement if necessary
*/
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Root
public static class AtomLink
{
@Attribute
private String href;
@Attribute
private String rel;
@Attribute
private String type;
// Ctor's / getter / setter ...
}
}
所有内部类也可以像普通类一样实现。如果事情(反)序列化很复杂,您也可以在Converter 中使用Serializer。
用法
最后是一个演示:
final String xml = " <channel>\n"
+ " <title>The Title</title>\n"
+ " <link>http://www.someurl.com</link>\n"
+ " <description>Some description</description>\n"
+ " <atom:link href=\"http://dunno.com/rss.xml\" rel=\"self\" type=\"application/rss+xml\" xmlns:atom=\"http://www.w3.org/2005/Atom\" />\n"
+ " ....\n"
+ " ....\n"
+ " </channel>\n";
Serializer ser = new Persister(new AnnotationStrategy());
// ^----- Important! -----^
Channel c = ser.read(Channel.class, xml);
System.out.println(c);
请注意Converter 需要Strategy(有关详细信息,请参阅上面的链接);我使用了AnnotationStrategy,因为你可以简单地使用@Convert()。 xmlns 必须在 XML 中的某处定义,否则您将捕获异常;我把它放到<atom:link … />这里。
输出
Channel{title=The Title, link=http://www.someurl.com, description=Some description, atomLink=AtomLink{href=http://dunno.com/rss.xml, rel=self, type=application/rss+xml}}