我遵循 Blaise Doughan 提出的概念,但没有依恋的编组:
我让a
XmlAdapter转换
byte[]为
URI-reference并返回,而引用则指向存储原始数据的单独文件。然后将XML文件和所有二进制文件放入一个zip文件中。
它类似于OpenOffice和ODF格式的方法,实际上是一个很少包含XML和二进制文件的zip。
(在示例代码中,没有写入任何实际的二进制文件,也没有创建zip。)
绑定文件
import java.net.*;import java.util.*;import javax.xml.bind.annotation.*;import javax.xml.bind.annotation.adapters.*;final class Bindings { static final String SCHEME = "storage"; static final Class<?>[] ALL_CLASSES = new Class<?>[]{ Root.class, RawRef.class }; static final class RawRepository extends XmlAdapter<URI, byte[]> { final SortedMap<String, byte[]> map = new TreeMap<>(); final String host; private int lastID = 0; RawRepository(String host) { this.host = host; } @Override public byte[] unmarshal(URI o) { if (!SCHEME.equals(o.getScheme())) { throw new Error("scheme is: " + o.getScheme() + ", while expected was: " + SCHEME); } else if (!host.equals(o.getHost())) { throw new Error("host is: " + o.getHost() + ", while expected was: " + host); } String key = o.getPath(); if (!map.containsKey(key)) { throw new Error("key not found: " + key); } byte[] ret = map.get(key); return Arrays.copyOf(ret, ret.length); } @Override public URI marshal(byte[] o) { ++lastID; String key = String.valueOf(lastID); map.put(key, Arrays.copyOf(o, o.length)); try { return new URI(SCHEME, host, "/" + key, null); } catch (URISyntaxException ex) { throw new Error(ex); } } } @XmlRootElement @XmlType static final class Root { @XmlElement final List<RawRef> element = new linkedList<>(); } @XmlType static final class RawRef { @XmlJavaTypeAdapter(RawRepository.class) @XmlElement byte[] raw = null; }}Main.java
import java.io.*;import javax.xml.bind.*;public class _Run { public static void main(String[] args) throws Exception { JAXBContext context = JAXBContext.newInstance(Bindings.ALL_CLASSES); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Unmarshaller unmarshaller = context.createUnmarshaller(); Bindings.RawRepository adapter = new Bindings.RawRepository("myZipVFS"); marshaller.setAdapter(adapter); Bindings.RawRef ta1 = new Bindings.RawRef(); ta1.raw = "THIS IS A STRING".getBytes(); Bindings.RawRef ta2 = new Bindings.RawRef(); ta2.raw = "THIS IS AN OTHER STRING".getBytes(); Bindings.Root root = new Bindings.Root(); root.element.add(ta1); root.element.add(ta2); StringWriter out = new StringWriter(); marshaller.marshal(root, out); System.out.println(out.toString()); }}输出量
<root> <element> <raw>storage://myZipVFS/1</raw> </element> <element> <raw>storage://myZipVFS/2</raw> </element></root>



