【问题标题】:JAXB - how to marshal a whole XML section to a stringJAXB - 如何将整个 XML 部分编组为字符串
【发布时间】:2015-07-10 19:41:33
【问题描述】:

我有一个 XML 文件:

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

我希望 JAXB 将其编组到以下对象:

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

其中baz 将是XML 中的实际baz 部分作为字符串。即:

...

怎么做?

【问题讨论】:

标签: java xml jaxb


【解决方案1】:

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

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

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

    String bar;
}

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

Adapter 只是执行一个简单的 dom 序列化,没什么特别的。您可以改为对内容使用 JAXB 模型并对其进行序列化。你也不需要@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)));
}

【讨论】:

  • 谢谢。但是我怎样才能写一个可以映射到你展示的Java类的xsd(Foo)?
猜你喜欢
  • 2019-02-14
  • 2020-08-04
  • 2018-01-06
  • 2017-04-28
  • 2015-03-25
  • 1970-01-01
  • 2013-01-24
  • 2012-09-12
相关资源
最近更新 更多