gpt4 book ai didi

jaxb - 如何在 JAXB 中映射只 Root过的 XML

转载 作者:行者123 更新时间:2023-12-01 15:55:27 26 4
gpt4 key购买 nike

我想知道如何在 JAXB 中映射只有根元素的 XML

<size>4</size>

最佳答案

这样的事情怎么样:

@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>

关于jaxb - 如何在 JAXB 中映射只 Root过的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20443702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com