如何在JAXB中仅使用根映射XML

时间:2013-12-07 16:30:19

标签: jaxb

我想知道如何映射只有JAXB

中的根元素的XML
<size>4</size>

1 个答案:

答案 0 :(得分:3)

这样的事情怎么样:

@XmlRootElement
static class Size {
    @XmlValue String textNode;
}


@Test
public void jaxbRootTextNode() throws JAXBException, IOException {
    try (ByteArrayInputStream is = 
            new ByteArrayInputStream("<size>4</size>"
                    .getBytes(StandardCharsets.UTF_8))) {
        JAXBContext c = JAXBContext.newInstance(Size.class);
        Unmarshaller um = c.createUnmarshaller();
        Size s = (Size) um.unmarshal(is);
        System.out.println("Text: " + s.textNode);
        System.out.println();
        s.textNode = "5";
        Marshaller m = c.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        m.marshal(s, System.out);
    }
}

打印:

Text: 4

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<size>5</size>