Create an element from its name in Java
Description
The following code shows how to create an element from its name.
Example
//from w ww . jav a 2 s. c o m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder loader = factory.newDocumentBuilder();
Document document = loader.newDocument();
Element root = document.createElement("order");
root.setAttribute("src", "java2s.com");
document.appendChild(root);
System.out.println(root +" "+ root.getAttribute("src"));
System.out.println(document);
}
}
The code above generates the following result.