Java HTML / XML How to - Parse a String containing XML in Java and retrieve the value of the root node








Question

We would like to know how to parse a String containing XML in Java and retrieve the value of the root node.

Answer

import java.io.StringReader;
/*from   w  ww.  j  a  v a2s. co m*/
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

public class Main {

  public static void main(String[] args) throws Exception {
    String xmlString = "<message>HELLO!</message> ";
    JAXBContext jc = JAXBContext.newInstance(String.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    StreamSource xmlSource = new StreamSource(new StringReader(xmlString));
    JAXBElement<String> je = unmarshaller.unmarshal(xmlSource, String.class);
    System.out.println(je.getValue());
  }

}