Create and add Attribute to an Element


import java.io.StringWriter;

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.DOMImplementation;
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 builder = factory.newDocumentBuilder();
    DOMImplementation impl = builder.getDOMImplementation();
    Document doc = impl.createDocument(null, null, null);
    Element e1 = doc.createElement("api");
    doc.appendChild(e1);
    Element e2 = doc.createElement("java");
    e1.appendChild(e2);

    e2.setAttribute("url", "http://www.domain.com");
    DOMSource domSource = new DOMSource(doc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(domSource, sr);
    System.out.println(sw.toString());
  }
}
Home 
  Java Book 
    Runnable examples  

XML DOM:
  1. Creating XML Element and add to Document
  2. Create and add Attribute to an Element
  3. Parse an XML File with DOM
  4. Parse an XML file with custom error handler
  5. Parse an XML string with DOM and StringReader.
  6. Visit all nodes from DOM
  7. Visit all nodes from DOM and output node type