I used JAXB to create a very complicated .xml file which I saved on the drive. I also manually made an .xsl file which is my template.
How do I now programmatically use the above two to create an html output file ?
I tried various things and maybe I'm just tired but I can't even successfully open the .xml file into a Document.
Does someone have a working example ? I would greatly appreciate it! Thanks :)
I tried various things, including the official code examples but I can't find a working example. Nothing but null pointer exceptions. :(
The smallest working example I can give you:
import java.io.File;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class UseXMLToHTML {
public static void main(String[] args) throws TransformerException {
StreamResult result = new StreamResult(new File("output.html"));
StreamSource source = new StreamSource(new File("input.xml"));
StreamSource xslt = new StreamSource(new File("transform.xslt"));
Transformer transformer = TransformerFactory.newInstance().newTransformer(xslt);
transformer.transform(source, result);
}
}
This would probably do the trick;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
public class TestMain {
public static void main(String[] args) throws IOException, URISyntaxException, TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
Source xslt = new StreamSource(new File("transform.xslt"));
Transformer transformer = factory.newTransformer(xslt);
Source text = new StreamSource(new File("input.xml"));
transformer.transform(text, new StreamResult(new File("output.xml")));
}
}
Consider trying out stuff from these urls:
http://www.w3schools.com/xsl/tryxslt.asp?xmlfile=cdcatalog&xsltfile=cdcatalog
http://www.w3schools.com/xsl/tryxslt_result.asp?xmlfile=cdcatalog&xsltfile=cdcatalog
Related
I have managed to export a CSV file using JAVA. Now, I want those CSV files to be saved because I noticed that if I do not manually save them, I cannot use my CSV files to connect with other programs and do things with them. Please take a look, and help me out. Thank you !!!
package edi.converter.main;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import edi.converter.outbound.sqlserver.OutboundProcess;
public class MainAppConverter {
public static void main(String[] args) throws Exception {
Result outputTarget = new StreamResult(new File("C:\\Users\\Khoa S Tran\\Desktop\\out.csv"));
Result outputTarget1 = new StreamResult(new File("C:\\Users\\Khoa S Tran\\Desktop\\out1.csv"));
File stylesheet = new File("C:\\Users\\Khoa S Tran\\Desktop\\style.xsl");
File xmlSource = new File("C:\\Users\\Khoa S Tran\\Desktop\\data.xml");
File xmlSource1 = new File("C:\\Users\\Khoa S Tran\\Desktop\\data1.xml");
// it is noted that it is impossible/challlenging to combine xml files then export them to one csv
//suggestion will be concatenate multiple csv files together
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlSource);
Document document1 = builder.parse(xmlSource1);
StreamSource stylesource = new StreamSource(stylesheet);
Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);
Source source = new DOMSource(document);
Source source1 = new DOMSource(document1);
transformer.transform(source, outputTarget);
//OutboundProcess.trytoExportSQL();
transformer.transform(source1, outputTarget1);
}
}
Bottom line is I have 2 XML files, I want to read them, combine them together, and export them to 1 single CSV file.
In case you might wonder where I can find the source code for concatenating 2 CSV's: How to merge multiple csv files into one in Java
I'm in a part of an application where I have an access to the XmlStreamReader which is representing the XML file needed to be fully read into a String.
Is there a way to obtain the XML content without building another XmlStreamReader or using another stream on the file?
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
private String getOuterXml(XMLStreamReader xmlr) throws TransformerConfigurationException,
TransformerFactoryConfigurationError, TransformerException
{
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StringWriter stringWriter = new StringWriter();
transformer.transform(new StAXSource(xmlr), new StreamResult(stringWriter));
return stringWriter.toString();
}
The following code
import java.io.File;
import java.io.FileReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
public class Demo {
public static void main(String[] args) throws Exception {
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("out.xml"));
xsr.nextTag(); // Advance to statements element
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
while(xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
t.transform(new StAXSource(xsr), new StreamResult("result.txt"));
}
}
}
produces some txt, and on the first line of it there are processing instructions (<?xml version="1.0">). Where do they come from and how to get rid of them? And how to manipulate them?
You can disable the creation of the xml declaration by setting the output properties on the transformer:
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
If you want to generate text files from the xml then you probably want to specify an XSLT source in the TransformerFactory.newInstance call and set the output properties in that XSLT.
The line <?xml version="1.0"?> is an xml declaration. According to the W3C XML Recommendation
XML documents SHOULD begin with an XML declaration which specifies the version of XML being used.
it is supposed to be there (albeit not mandatory).
Btw. in a strict technical sense it is not a processing instruction.
Edit: the encoding can be changed with:
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
I am trying to write to a XML file. It runs correctly in eclipse. The file is located at ca/ism/wen/domain folder (together with my user.java). However, it is throws FileNotFoundException when I run the exported runnable jar file. Is there way to write to an xml file in the jar file? Following is my code.
package ca.ism.wen.utils;
import java.io.File;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import ca.ism.wen.domain.User;
/**
* Load XML file
*
*/
public class XmlFactory {
private static Document dom;
//private static File file = new File(User.class.getResource("UserRDP.xml").getPath());
private static InputStream filei = User.class.getResourceAsStream("UserRDP.xml");
private static File fileo = new File(User.class.getResource("UserRDP.xml").getPath());
static {
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(filei);
} catch (Exception e){
e.printStackTrace();
}
}
public static Document getDom(){
return dom;
}
public static void saveDom(){
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
DOMSource ds = new DOMSource(dom);
StreamResult sr = new StreamResult(fileo);
trans.transform(ds, sr);
} catch (Exception e){
throw new RuntimeException(e.getMessage(),e);
}
}
}
If I have to put my XML file externally somewhere, I want to get a runnable file and put it in a folder under my whole project (just like normal software), cause it may be deployed to other person's machine later. Is that possible?
I believe you need to provide an implementation for javax.xml.parsers.DocumentBuilderFactory as a third party library to your classpath as per the javadoc.
Try
new File(User.class.getResource("UserRDP.xml").toURI());
The appropriate constructor of the File should be used to locate the resource. This approach only works with exploded jar. You cannot write to a jar, however you can read from it using jar protocol.
I would like to know how do I overwrite and existing element in Java using dom parser. for example, I have the file
I am trying to overwrite the element and replace it with the element
Thanks.
Algorithm is easy:
Read a file and parse it to XML document
Make any changes you want
Overwrite existing file with new content
See my example:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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.Document;
import org.w3c.dom.Element;
public class DomProgram {
public static void main(String[] args) throws Exception {
File xmlFile = new File("C:\\test.xml");
Document document = readXmlDocument(xmlFile);
makeChanges(document);
Transformer transformer = createXmlTransformer();
overwriteXmlFile(xmlFile, document, transformer);
}
private static void overwriteXmlFile(File xmlFile, Document document,
Transformer transformer) throws FileNotFoundException,
TransformerException {
StreamResult result = new StreamResult(new PrintWriter(
new FileOutputStream(xmlFile, false)));
DOMSource source = new DOMSource(document);
transformer.transform(source, result);
}
private static Transformer createXmlTransformer() throws Exception {
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
return transformer;
}
private static void makeChanges(Document document) {
Element root = document.getDocumentElement();
root.setAttribute("test", "testvalue");
}
private static Document readXmlDocument(File xmlFile) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlFile);
return document;
}
}
Example XML file:
<note>
<to>Ebele</to>
<from>mykhaylo</from>
<heading>Reminder</heading>
<body>Read about problem before you ask ;)</body>
</note>
Also see:
Simple Java DOM XML Example
How To Read XML File In Java – (DOM Parser)