Node: appendChild(Node newChild) : Node « org.w3c.dom « Java by API






Node: appendChild(Node newChild)

/*
 
 <?xml version="1.0" encoding="UTF-8"?>
 <book id="javanut4">
    <chapter>
       <title>Chapter 1</title>
       <para/>
    </chapter>
    <chapter>
       <title>Chapter 2</title>
       <para/>
    </chapter>
    <chapter>
       <title>Chapter 3</title>
       <para/>
    </chapter>
 </book>
 */

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class MainClass {
  public static void main(String[] args) throws Exception{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document document = db.newDocument();

    Element book = document.createElement("book"); 
    book.setAttribute("id", "javanut4");           
    document.appendChild(book);                    
    for(int i = 1; i <= 3; i++) {                  
        Element chapter = document.createElement("chapter");
        Element title = document.createElement("title");
        title.appendChild(document.createTextNode("Chapter " + i));
        chapter.appendChild(title);
        chapter.appendChild(document.createElement("para"));
        book.appendChild(chapter);
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();

    DOMSource source = new DOMSource(document);          
    StreamResult result = new StreamResult(System.out);  

    transformer.transform(source, result);
  }
}

           
       








Related examples in the same category

1.Node.CDATA_SECTION_NODE
2.Node.COMMENT_NODE
3.Node.DOCUMENT_FRAGMENT_NODE
4.Node.DOCUMENT_NODE
5.Node.DOCUMENT_TYPE_NODE
6.Node.ELEMENT_NODE
7.Node.ENTITY_NODE
8.Node.ENTITY_REFERENCE_NODE
9.Node.NOTATION_NODE
10.Node.PROCESSING_INSTRUCTION_NODE
11.Node.TEXT_NODE
12.Node: getChildNodes()
13.Node: getFirstChild()
14.Node: getNextSibling()
15.Node: getNodeName()
16.Node: getNodeType()
17.Node: getNodeValue()
18.Node: hasAttributes()