Java HTML / XML How to - Build an XML Document by text and tag name








Question

We would like to know how to build an XML Document by text and tag name.

Answer

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/*from   ww w .  jav a 2 s.  c  o m*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); 
        dFactory.setValidating( false ); 
        DocumentBuilder dBuilder = dFactory.newDocumentBuilder(); 
        Document dDoc = dBuilder.newDocument(); 

        // The root document element. 
        Element pageDataElement = dDoc.createElement("page-data"); 
        pageDataElement.appendChild(dDoc.createTextNode("Example Text.")); 

        dDoc.appendChild(pageDataElement); 

        System.out.println(dDoc.getDocumentElement().getTextContent());
    }
}