Create an XML file and attach an XSLTag(s): XMLXML
About cookies on this site
We use cookies to collect and analyze information on site performance and usage,
to provide social media features and to enhance and customize content and advertisements.
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
public class CreateXML {
public static void main (String args[]) {
new CreateXML().doit();
}
public void doit () {
try{
Document xmldoc = initXML();
Element root = xmldoc.getDocumentElement();
process(xmldoc, root);
StreamResult out = new StreamResult("howto.xml");
writeXML(xmldoc, out);
}
catch (Exception e) { e.printStackTrace(); }
}
public Document initXML() throws ParserConfigurationException{
// JAXP + DOM
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
return impl.createDocument(null, "HOWTOS", null);
}
public void process(Document xmldoc, Element root) {
Element e0 = xmldoc.createElement("TOPIC");
Element e1 = xmldoc.createElement("TITLE");
Node n1 = xmldoc.createTextNode("Java");
e1.appendChild(n1);
Element e2 = xmldoc.createElement("URL");
Node n2 = xmldoc.createTextNode
("http://www.rgagnon/topics/java-xml.html");
e2.appendChild(n2);
e0.appendChild(e1);
e0.appendChild(e2);
root.appendChild(e0);
}
public void writeXML(Document xmldoc, StreamResult out)
throws TransformerConfigurationException, TransformerException
{
DOMSource domSource = new DOMSource(xmldoc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty
(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
// we want to pretty format the XML output
transformer.setOutputProperty
("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//
transformer.transform(domSource, out);
}
}