I've just begun learning DOM XML , so I'm currently at a very beginner level.
I have an existing XML file that I would like to add an additional node to before saving it to another variable.
how I can append new node in this file.
now this code is overwrite new data over old data
The code looks like this:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
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;
public class VerbXMLWriter
{
static String EVerb3;
static String englishTranslate3;
public void VerbXMLWriter(String EVerb, String englishTranslate )
{
EVerb3 = EVerb;
englishTranslate3=englishTranslate;
File xmlFile = new File("VerbDB.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element root = document.createElement("Verb");
document.appendChild(root);
Element verb = document.createElement(EVerb3);
verb.setAttribute("EnglishTranslate",englishTranslate3);
root.appendChild(verb);
Source xmlSource = new DOMSource( document );
Result result = new StreamResult( new FileOutputStream(xmlFile) );
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer =
transformerFactory.newTransformer();
transformer.setOutputProperty( "indent", "yes" );
transformer.transform( xmlSource, result );
}
catch(TransformerFactoryConfigurationError factoryError )
{
factoryError.printStackTrace();
}
catch (ParserConfigurationException pc)
{
pc.printStackTrace();
}
catch (IOException io)
{
io.printStackTrace();
}
catch(Exception excep )
{
excep.printStackTrace();
}
}
}
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Verb>
<Play EnglishTranslate="playing" />
</Verb>
Edited by: itb402 on Mar 9, 2008 6:05 AM