JAVA XML

JavaXml Projects

JavaXml Project 1

JavaXml Examples

JavaXml EXAMPLE

adplus-dvertising
DOM Child Elements Creation
Previous Home Next

In this topics we are going to create the child element of DOM. firstly we are create the blank document which is add into the root element to it. after that we are creating the child elements.

<?xml version="1.0" encoding="UTF-8" ?>
<root>
<!--comment-->
<Child attribute1="The Attribute 1 Values" />
</root>

The creation of the child show in steps

  1. Firstly create instance of DocumentBuilderFactory
  2. 
    DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
    
  3. Get the DocumentBuilder
  4. DocumentBuilder pars = fact.newDocumentBuilder();
    
  5. Create blank DOM Document
  6. Document docu = pars.newDocument();
    
  7. Creating the Root Elements.
  8. Element root = docu.createElement("root");
    
  9. Append to the child Element in Root
  10. 
    docu.appendChild(root);
    
  11. create child element
  12. Element childElement = docu.createElement("Child");
    
  13. Add the atribute in the child
  14. childElement.setAttribute("attribute1","Attribute 1 values");
    root.appendChild(childElement);
    

Example

package r4r;
import org.w3c.dom.*;
import javax.xml.*;
import javax.xml.parsers.*; 
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 
public class childcreattest {
	public static void main(String[] args) 
	  {
	  try{
	   DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
	  DocumentBuilder docBuild = fact.newDocumentBuilder();
	  Document docu = docBuild.newDocument();
	  Element root = docu.createElement("root");
	  docu.appendChild(root);
	  Comment com = docu.createComment("-----comment-----");
	  root.appendChild(com);
	  Element childElement = docu.createElement("Child");
	  childElement.setAttribute("attribute1","The Attribute1 Values");
	  root.appendChild(childElement);
	  TransformerFactory tranFact = TransformerFactory.newInstance(); 
	  Transformer tform = tranFact.newTransformer(); 
	  Source sr = new DOMSource(docu); 
	  Result rst = new StreamResult(System.out); 
	  tform.transform(sr, rst); 
	  }catch(Exception e){
	  System.out.println(e.getMessage());
	  }
	  }
}
Previous Home Next