0

对于当前项目,我需要将 XML 数据写入 ByteBuffer 以将输出 XML 写入二进制格式(例如 .dat)。

对于与我的xml元素对应的每个java对象,是否有一个lib或类将其属性的值写入ByteBuffer(或一些类似的实现),同时尊重属性类型(int -> buffer.putInt(intAttribute ) ...

PS:理想情况下,我需要这种方法将每个元素序列的大小放在这些元素的值之前

编辑:这是我想要的一个具体例子

假设我有以下类定义 walker_template xml 元素

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"routestep"
})
@XmlRootElement(name = "walker_template")
public class WalkerTemplate {

protected List<Routestep> routestep;

@XmlAttribute(name = "route_id")
protected String routeId;

public List<Routestep> getRoutestep() {
    if (routestep == null) {
        routestep = new ArrayList<Routestep>();
    }
    return this.routestep;
}

RouteStep 是:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
@XmlRootElement(name = "routestep")
public class Routestep {

@XmlAttribute
protected Integer step;
@XmlAttribute
protected Float x;
@XmlAttribute
protected Float y;
@XmlAttribute
protected Float z;

这些类定义了我通常使用 JAXB 编组的对象,然后将其写入输出文件。

marshaller.marshal(templatesToWrite, myXMLStreamWriter);

我现在想要的是以二进制格式写入这些对象的数据。

执行此操作的方法应如下所示(对于此示例):

ByteBuffer buffer = new ByteBuffer.allocate(size);
buffer.putInt(myWalkerTemplate.getRouteId());
buffer.putInt(myWalkerTemplate.getRouteSteps().size());
for (Routestep step : myWalkerTemplate.getRouteSteps()) {
    buffer.putFloat(step.getX());
    buffer.putFloat(step.getY());
    buffer.putFloat(step.getZ());
}

那么,是否有任何库/类可以为任何对象自动执行此操作,当然这些对象的类(例如使用 JAXBContext 的 Marshaller)。

谢谢

4

0 回答 0