gpt4 book ai didi

java - 从 XMLType 标记的 Java 类中提取 XML

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:54 26 4
gpt4 key购买 nike

我有一个 Java 类,它被注释为 XMLType

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "fooClass", propOrder = {
"fooElement1",
"fooElement2"
})
public class fooClass{
@XmlElement(required = true)
protected String fooElement1;

@XmlElement(required = true)
protected String fooElement2;

.....

}

我希望能够在 Java 中提取 XML 表示(最好是流,但字符串也可以),大致如下:

fooClass foo = new fooClass()
foo.setFooElement1("baba")
foo.setFooElement2("abab")

String xmlRep = DomSomething(foo)

知道该怎么做吗?

谢谢!

最佳答案

类似于:

try {
JAXBContext jaxbContext = JAXBContext.newInstance(fooClass.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
jaxbMarshaller.marshal(fooInstance, ps);

String result = new String(baos.toByteArray());

...
} catch (JAXBException e) {
...
}

关于java - 从 XMLType 标记的 Java 类中提取 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28348642/

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