简体   繁体   English

JAXB-如何将整个XML节编组为字符串

[英]JAXB - how to marshal a whole XML section to a string

I have an XML file: 我有一个XML文件:

<foo>
  <bar>...</bar>
  <baz attr="something>
    <child1>...</child1>
  </baz>
</foo>

And I want JAXB to marshal it to the following object: 我希望JAXB将其封送至以下对象:

@XmlRootElement
public class Foo {
    Bar bar;
    String baz;
}

Where baz will be the actual baz section from the XML as a string. 其中baz将是XML中来自字符串的实际baz节。 ie: 即:

<baz attr="something"> <child1>...</child1> </baz>

How can it be done? 如何做呢?

You can write an xmljavatype adapter for this kind of task. 您可以为此类任务编写xmljavatype适配器。

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

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

    String bar;
}

any is used to tell jaxb that any content is allowed here (avoiding an illegalannotation exception because jaxb can't handle interfaces) any用来告诉jaxb此处允许任何内容(避免非法注释异常,因为jaxb无法处理接口)

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();
    }
}

The Adapter performs just a simple dom serialization, nothing fancy. 适配器仅执行简单的dom序列化,没有花哨的事情。 You could instead use a JAXB model for the content and serialize that. 您可以改为使用JAXB模型作为内容并对其进行序列化。 Than you wouldn't need the @XmlAnyElement either. 比起您也不需要@XmlAnyElement

@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)));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM