XStream信号集合中的几种节点类型 [英] XStream several node types in signle collection

查看:33
本文介绍了XStream信号集合中的几种节点类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试反序列化此类 XML 文档:

I'm trying to deserialize such XML document:

<rootelem>
    <elementType1 arg1="..." />
    <elementType1 arg1="..." />
    <elementType1 arg1="..." />
    <elementType2 argA="..." argB="..." />
    <elementType2 argA="..." argB="..." />
    <elementType2 argA="..." argB="..." />
</rootelem>

默认情况下,XStream 只能解析这样的形式:

By default XStream can parse only such form:

<rootelem>
    <list1>
        <elementType1 arg1="..." />
        <elementType1 arg1="..." />
        <elementType1 arg1="..." />
    </list1>

    <list2>
        <elementType2 argA="..." argB="..." />
        <elementType2 argA="..." argB="..." />
        <elementType2 argA="..." argB="..." />
    </list>
</rootelem>

这是因为 XStream 为集合使用下一个格式:

This is because XStream use next format for collections:

<collection>
    <elem .... />
    <elem .... />
    <elem .... />
</collection>

和框架标签是强制性的.集合只能包含单一类型的节点.那么如何解析这样的 XML 文档呢?现在我已经为此编写了自己的转换器,但我想知道还有其他方法吗?

and frame tags are obligatory. Collection can contain only single type nodes. So how can I parse such XML document? Now I've written my own convertor for this but I wonder are there some other ways?

推荐答案

我认为 Implicit Collections 是适合您的解决方案.

I think that Implicit Collections is the solution for you.

http://x-stream.github.io/alias-tutorial.html#隐含

这是示例代码:

package com.thoughtworks.xstream;

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {

            Blog teamBlog = new Blog(new Author("Guilherme Silveira"));
            teamBlog.add(new Entry("first","My first blog entry."));
            teamBlog.add(new Entry("tutorial",
                    "Today we have developed a nice alias tutorial. Tell your friends! NOW!"));

            XStream xstream = new XStream();
            xstream.alias("blog", Blog.class);
            xstream.alias("entry", Entry.class);

            xstream.addImplicitCollection(Blog.class, "entries");

            System.out.println(xstream.toXML(teamBlog));
    }
}

结果:

<blog>
  <author>
     <name>Guilherme Silveira</name>
  </author>
  <entry>
     <title>first</title>
     <description>My first blog entry.</description>
  </entry>
  <entry>
     <title>tutorial</title>
     <description>
          Today we have developed a nice alias tutorial. Tell your friends! NOW!
     </description>
  </entry>
</blog>

这篇关于XStream信号集合中的几种节点类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆