0

I have the below code that appends to an xml file. The problem is that it includes the xml configuration line each time it appends along with the main element. It works fine for the first record added to the file because there is not previous existing elements. How would I modify this code to exclude those lines for an existing file with existing elements?

import java.io.FileWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.Document;
import org.w3c.dom.Element; 
import org.xml.sax.SAXException;
public class WriteXMLFile {

public static void main() throws ParserConfigurationException,SAXException,Exception{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();//
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();//

Document doc = docBuilder.newDocument();// this is difrent

Element rootElement = doc.createElement("Contacts");//
doc.appendChild(rootElement); // this is difrent

Element Contact1 = doc.createElement("Contact1");
rootElement.appendChild(Contact1);


Contact1.setAttribute("id","1");

Element firstname = doc.createElement("Name");
firstname.appendChild(doc.createTextNode(EmailFrame.name.getText()));
Contact1.appendChild(firstname); 

//Email Element
Element email = doc.createElement("Email");
email.appendChild(doc.createTextNode(EmailFrame.email.getText()));
Contact1.appendChild(email); 

// phone element
Element phone= doc.createElement("Phone");
phone.appendChild(doc.createTextNode(EmailFrame.phone.getText()));
Contact1.appendChild(phone);

//id element
Element id = doc.createElement("ID");
id.appendChild(doc.createTextNode(EmailFrame.id.getText()));
Contact1.appendChild(id); 

try{
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);


StreamResult result = new StreamResult(new FileWriter("C:/Users/steve/Desktop/xmlemail/Email.xml",true));

transformer.transform(source, result);
System.out.println("File saved!");

}
catch (TransformerException tfe) {
tfe.printStackTrace();
}
}}

1 Answer 1

1
  1. If you are looking for "overriding" the file then you shall use

StreamResult result = new StreamResult(new FileWriter("D:/tmp/Email.xml")); as boolean parameter just appends to the document.

  1. If you indeed want to append but don't want <?xml version="1.0" encoding="UTF-8" standalone="no"?> then you will have to "read" the file, get the root node and then add elements to the root node.

Remember if you just keep on adding nodes to the document and not to the root element, then even without <?xml version="1.0" encoding="UTF-8" standalone="no"?>, your xml will be invalid, as it will contain multiple root elements "contacts".

Something like:

    Document doc = null;
    Node rootElement = null;
    if (f.exists()) {
        doc = docBuilder.parse("C:/Users/steve/Desktop/xmlemail/Email.xml");
        rootElement = doc.getFirstChild();//

    } else {
        doc = docBuilder.newDocument();// this is difrent
        rootElement = doc.createElement("Contacts");//
        doc.appendChild(rootElement); // this is difrent
    }

And then save the document to file without appending.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.