对象到xml映射格式化为spring bean定义

时间:2011-11-16 23:19:40

标签: java spring xml-serialization

我正在寻找一种将java对象序列化为XML的方法,其格式与spring bean defination相同。例如,该类定义为:

package x.y.z;
class foo {
    String name;
    int counter;

    ...setter and getter omitted for simplicity ....
}

类foo的对象将被序列化为:

<bean id="" class="x.y.z.foo">
   <property name="name" value="some random value"/>
   <property name="counter" value="1" />
</bean>

目的是稍后我可以通过将xml复制/粘贴到spring上下文文件中将对象注入单元测试。

1 个答案:

答案 0 :(得分:0)

如果你可以使用注释,那么像Simple XML Serialization这样的东西可以做你喜欢的事情。我也喜欢XStream,但它可能不会让自己的XML与你的类结构不同。

http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php

你可能最好只编写一个marshal(),甚至是一个带有字符串缓冲区的脏代码:

public Element marshal() {
    StringBuffer sb = new StringBuffer();
    sb.append("\t<bean id="">\n");
        sb.append("\t\t<property name=\"").append(name).append(""/>\n");
    sb.append("\t</bean>\n");
    InputStream istream = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
    Document myDoc = new SAXBuilder().build(istream);
}

或更好的构建文档并添加元素。

然后输出

    // Save it to a file:
    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    java.io.FileWriter writer = new java.io.FileWriter(fileName);
    out.output(document, writer);
    writer.flush();
    writer.close();

我认为如果您的架构如此简单,但与XML不同,我可能会花费更多时间来尝试配置XML序列化程序,而不是只修复它。