用另一个元素包装XStream中的xml输出

时间:2012-07-04 19:14:38

标签: java xml serialization xstream

我有这堂课:

Class B {
  private String D;
  private String E;
}

使用XStream,我想生成这样的XML,其中元素A和B在XML中生成,即使它们不存在于java中。:

<A>
        <B>
                <C>
                        <D/>
                        <E/>
                </C>
        </B>
</A>

可能的?

2 个答案:

答案 0 :(得分:2)

您可以在XStream实例中实现并注册自定义转换器。 例如:

XStream xstream = new new XStream(...);
xstream.registerConverter(new BConverter());
xstream.toXML(new B(),new BufferedWriter(...));

转换器实现示例:

class BConverter implements com.thoughtworks.xstream.converters.Converter{

@Override
public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext mc) {
    B target=(B)o;
    writer.startNode("A");
    writer.startNode("B");
    writer.startNode("C");
    writer.startNode("D");
    writer.setValue(target.getD());
    writer.endNode();//end node D
    writer.startNode("E");
    writer.setValue(target.getE());
    writer.endNode();//end node E
    writer.endNode();//end node C
    writer.endNode();//end node B
    writer.endNode();//end node A
}

@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext uc) {
    //unmarshalizing logic here
}

@Override
public boolean canConvert(Class type) {
    return type.equals(B.class);
}

}

答案 1 :(得分:1)

注意:我是EclipseLink JAXB (MOXy)主管,是JAXB (JSR-222)专家组的成员。

由于您正在寻找基于注释的解决方案,因此您可能对MOXy中的@XmlPath扩展感兴趣。

<强>乙

@XmlPath注释允许您将映射指定为XPath。

package forum11334385;

import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement(name="A")
@XmlAccessorType(XmlAccessType.FIELD)
class B {

    @XmlPath("B/C/D/text()")
    private String D;

    @XmlPath("B/C/E/text()")
    private String E;

}

<强> jaxb.properties

要将MOXy指定为JAXB提供程序,您需要在与域模型相同的程序包中包含名为jaxb.properties的文件,并带有以下条目(请参阅:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)。

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

<强>演示

package forum11334385;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(B.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11334385/input.xml");
        B b = (B) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(b, System.out);
    }

}

<强> input.xml中/输出

<?xml version="1.0" encoding="UTF-8"?>
<A>
   <B>
      <C>
         <D>Foo</D>
         <E>Bar</E>
      </C>
   </B>
</A>

了解更多信息