add XML Items to a XML Document - Java XML

Java examples for XML:DOM Document

Description

add XML Items to a XML Document

Demo Code


//package com.java2s;
import java.io.File;

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 Document addXMLItems(File xmlfile, String tag)
            throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();// w w w .  j  av  a2 s .  c  om
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc;
        if (xmlfile.length() == 0) {
            doc = builder.newDocument();
            Element rootElement = doc.createElement(tag + "s");
            doc.appendChild(rootElement);
        } else {
            doc = builder.parse(xmlfile);
        }
        return doc;
    }
}

Related Tutorials