Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Create XML and Extend its Nodes

4.80/5 (3 votes)
17 Apr 2014CPOL 7.8K  
Creates an XML File, and extends its Node if it already exists

Introduction

This tip is all about writing an XML file and extending its nodes further, so that it can be extended well, upto an extent.

Well, we are all aware about Java, its technology/technologies, whatsoever we may represent, as well as its influence on us. Java binding with XML gives a clear view about the possibilities about the future technology/ technologies.

Background

Well, I started not so early, but hope to achieve it.

Here's the agenda - create an XML file, and write data into it. If it exists, extend the data. The alteration part will be done in the next post.

Using the Code

C++
import com.sun.corba.se.spi.activation.Server;
import com.sun.deploy.xml.XMLNode;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javax.swing.JApplet;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
 
 
private void CreateXMLFile()
    {
        try 
        {
        String xmlFilePath = "/Users/saahilpriya/Desktop/myxmlfile.xml"; 
            File fp = new File (xmlFilePath);
            
            if ( !fp.exists() )
            {
                DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();

                Document document = documentBuilder.newDocument();
                Element root = document.createElement("Register_Server");
                document.appendChild(root);

                Element profiler = document.createElement("Projects");
                root.appendChild(profiler);

    //            Attr attr = document.createAttribute("id");
    //            attr.setValue("10");
    //            employee.setAttributeNode(attr);

                Element projName = document.createElement("Project_Name");
                projName.appendChild(document.createTextNode("Proj1"));
                profiler.appendChild(projName);
                
                Element SPName = document.createElement("SharePointServer");
                SPName.appendChild(document.createTextNode("https://abc.sharepoint.com"));
                profiler.appendChild(SPName);

                Element Online = document.createElement("IsOnline");
                Online.appendChild(document.createTextNode("YES"));
                profiler.appendChild(Online);

                Element UserName = document.createElement("User_Name");
                UserName.appendChild(document.createTextNode("saahil1@abc.onmicrosoft.com"));
                profiler.appendChild(UserName);

                Element pwd = document.createElement("Password");
                pwd.appendChild(document.createTextNode("PWD1"));
                profiler.appendChild(pwd);

                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource domSource = new DOMSource(document);
                StreamResult streamResult = new StreamResult(fp);

                transformer.transform(domSource, streamResult);
            }
            else
            {
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document document = documentBuilder.parse(fp);
                
                Element root = document.getDocumentElement();
                //Node root = root1.getLastChild();
        
                //Element root = document.createElement("Register_Server");
                //document.appendChild(root);

                Element profiler = document.createElement("Projects");
                root.appendChild(profiler);

    //            Attr attr = document.createAttribute("id");
    //            attr.setValue("10");
    //            employee.setAttributeNode(attr);

                Element projName = document.createElement("Project_Name");
                projName.appendChild(document.createTextNode("Proj3"));
                profiler.appendChild(projName);
                
                Element SPName = document.createElement("SharePointServer");
                SPName.appendChild(document.createTextNode("https://abc.sharepoint.com"));
                profiler.appendChild(SPName);

                Element Online = document.createElement("IsOnline");
                Online.appendChild(document.createTextNode("YES"));
                profiler.appendChild(Online);

                Element UserName = document.createElement("User_Name");
                UserName.appendChild(document.createTextNode("saahilpriya@abc.onmicrosoft.com"));
                profiler.appendChild(UserName);

                Element pwd = document.createElement("Password");
                pwd.appendChild(document.createTextNode("PWD2"));
                profiler.appendChild(pwd);

                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource domSource = new DOMSource(document);
                StreamResult streamResult = new StreamResult(fp);

                transformer.transform(domSource, streamResult);
            }
            
            System.out.println("Done creating XML File");
        } 
        catch (ParserConfigurationException pce) 
        {
            pce.printStackTrace();
        }
        catch (TransformerException tfe)
        {
            tfe.printStackTrace();
        }
        catch (SAXException sax)
        {
            sax.printStackTrace();
        }
        catch (IOException iox)
        {
            iox.printStackTrace();
        }
    } 

Points of Interest

I spent many days searching and executing the code in the right way. Hope the code works well in your case.

History

Updates for modifying the written nodes will be done in the next tip. Until then, HAPPY JAVA-ING.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)