2

我需要编组一个包含 String 变量的对象。
字符串变量。包含一个 XML 文档,并通过转义到 XMLElement 进行编组。

我想将 String 变量编组为 base64 格式,然后在解组时返回 String。

这可能吗?

4

1 回答 1

8

You can use an XmlAdapter to convert the String to/from a byte[] during the marshalling/unmarshalling process. By default JAXB will represent a byte[] as base64Binary.

XmlAdapter (Base64Adapter)

Below is an XmlAdapter that will convert between a String and a byte[].

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class Base64Adapter extends XmlAdapter<byte[], String> {

    @Override
    public String unmarshal(byte[] v) throws Exception {
        return new String(v);
    }

    @Override
    public byte[] marshal(String v) throws Exception {
        return v.getBytes();
    }

}

Java Model (Foo)

The XmlAdapter is configured using the @XmlJavaTypeAdapter annotation.

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class Foo {

    private String bar;

    @XmlJavaTypeAdapter(Base64Adapter.class)
    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

}

Demo

In the demo code below we will create an instance of Foo and marshal it to XML.

import javax.xml.bind.*;

public class Demo {

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

        Foo foo = new Foo();
        foo.setBar("<abc>Hello World</abc>");

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

}

Output

Below is the output from running the demo code:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo>
    <bar>PGFiYz5IZWxsbyBXb3JsZDwvYWJjPg==</bar>
</foo>
于 2013-10-17T11:32:33.623 回答