Java HTML / XML How to - Output org.w3c.dom.Element to string format








Question

We would like to know how to output org.w3c.dom.Element to string format.

Answer

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.namespace.QName;
/*from   w  w  w. j a  v a2s  . c o  m*/
@XmlRootElement
public class Main {

  @XmlAttribute
  private String test;

  @XmlElement
  private int x;

  public Main() {
  }

  public Main(String test) {
    this.test = test;
  }

  public static void main(String[] args) throws Exception {
    JAXBContext jxbc = JAXBContext.newInstance(Main.class);
    Marshaller marshaller = jxbc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
    marshaller.marshal(new JAXBElement(new QName("root"), Main.class,
        new Main("test")), System.out);
  }
}