Java JAXB—如何将整个XML节封送到字符串

Java JAXB—如何将整个XML节封送到字符串,java,xml,jaxb,Java,Xml,Jaxb,我有一个XML文件: <foo> <bar>...</bar> <baz attr="something> <child1>...</child1> </baz> </foo> 其中baz将是XML中作为字符串的实际baz部分。i、 e: <baz attr="something"> <child1>...</child1> </baz&

我有一个XML文件:

<foo>
  <bar>...</bar>
  <baz attr="something>
    <child1>...</child1>
  </baz>
</foo>
其中
baz
将是XML中作为字符串的实际
baz
部分。i、 e:

<baz attr="something"> <child1>...</child1> </baz> ...
如何做到这一点?

您可以为此类任务编写xmljavatype适配器

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {

    @XmlJavaTypeAdapter(BazXmlAdapter.class)
    @XmlAnyElement
    String baz;

    String bar;
}
any用于告诉jaxb此处允许任何内容(避免IllegaAnnotation异常,因为jaxb无法处理接口)


可能是重复的谢谢。但是如何编写一个可以映射到您展示的Java类(
Foo
)的xsd呢?
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {

    @XmlJavaTypeAdapter(BazXmlAdapter.class)
    @XmlAnyElement
    String baz;

    String bar;
}
public class BazXmlAdapter extends XmlAdapter<Element, String> {

    @Override
    public Element marshal(String v) throws Exception {
        // TODO NYI Auto-generated method stub
        throw new UnsupportedOperationException();
    }

    @Override
    public String unmarshal(Element node) throws Exception {
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        StringWriter buffer = new StringWriter();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(node), new StreamResult(buffer));
        return buffer.toString();
    }
}
@Test
public void unmarshalPartialXml() throws Exception {
    String partial = "<baz attr=\"something\"/>";
    String xml = "<foo><bar>asdf</bar>" + partial + "</foo>";

    Unmarshaller unmarshaller = JAXBContext.newInstance(Foo.class)
        .createUnmarshaller();

    Foo foo = (Foo) unmarshaller.unmarshal(new StringReader(xml));

    assertThat(foo.baz, is(equalTo(partial)));
}