Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从XMLType标记的Java类中提取XML_Java_Xml - Fatal编程技术网

从XMLType标记的Java类中提取XML

从XMLType标记的Java类中提取XML,java,xml,Java,Xml,我有一个Java类,它被注释为XMLType @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "fooClass", propOrder = { "fooElement1", "fooElement2" }) public class fooClass{ @XmlElement(required = true) protected String fooElement1; @XmlElement(

我有一个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) {
    ...
}

您可能应该创建一个JAXB上下文,看看这个:创建一个JAXB上下文可能很昂贵,您可能不想在每次调用时都这样做……我之前已经创建了JAXB内容,所以它可能是值得的。这不起作用,因为fooClass没有XMLRootElement,我不能添加XMLRootElement,还有其他想法吗?@jonatzin刚刚偶然发现了这一点,希望这能帮助您在没有注释的情况下设置JAXB…-但也许这没什么帮助