I want to store sql query in tree format in xml file.I wrote a code which split the code into different tokens and store it in xml file.I am storing keywords like "select",from,where etc as xmlelements and the values of these keywords as textnodes inside corresponding elements.When the query contains single single statement it works as i need.but when nested query occurs i want to store the nested query inside "where" element.In that case the code didn't works properly.I am hereby attaching the code.
Can anyone point out logical mistakes in my code????
Second problem is that when i try to store the xmldata in "CreateFiles.xml" file ,the file is not displaying in the corresponding folder.what is the reason for that?
CreateXml.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Work;
import java.io.File;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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;
/**
*
* #author user
*/
public class Createxmls {
public void CreateXML() throws ParserConfigurationException, TransformerConfigurationException, TransformerException {
DocumentBuilderFactory documentFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentFactory
.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("SQLStatement");
document.appendChild(rootElement);
Element stmt = document.createElement("SQLStatement");
rootElement.appendChild(stmt);
Element Element = document.createElement("null");
String tokens[] = {"select", "max(id)", "from", "facedictionary", "where", "id = (",
"select", "id", "from", "facedetails", "where", "id like 34 group by id)"};
for (int i = 0; i < tokens.length; i++) {
System.out.println("tok:" + tokens[i]);
if (tokens[i].equalsIgnoreCase("select") || tokens[i].equalsIgnoreCase("from") || tokens[i].equalsIgnoreCase("where")) {
Element = document.createElement(tokens[i]);
stmt.appendChild(Element);
} else {
Element.appendChild(document.createTextNode(tokens[i]));
stmt.appendChild(Element);
}
}
String xmlstring = "";
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult streamResult = new StreamResult(new File(
"createFile.xml"));
StringWriter sw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.transform(new DOMSource(document), new StreamResult(sw));
xmlstring = sw.toString();
System.out.println(xmlstring);
DOMSource domSource = new DOMSource(stmt);
transformer.transform(domSource, streamResult);
System.out.println("File saved to specified path!");
}
public static void main(String arg[]) {
try {
Createxmls xml = new Createxmls();
xml.CreateXML();
} catch (ParserConfigurationException ex) {
Logger.getLogger(Createxmls.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerConfigurationException ex) {
Logger.getLogger(Createxmls.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerException ex) {
Logger.getLogger(Createxmls.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
When i displayed the contents of xml file for the query:
"select max(id) from facedictionary where id = (select id from facedetails where id like 34 group by id))
The result i got
<?xml version="1.0" encoding="UTF-8"?>
-<SQLStatement>
<select>max(id)</select>
<from>facedictionary</from>
<where>id = (</where>
<select>id</select>
<from>facedetails</from>
<where>id like 34 group by id)</where>
</SQLStatement>
The result i need:
<?xml version="1.0" encoding="UTF-8"?>
-<SQLStatement>
<select>max(id)</select>
<from>facedictionary</from>
<where>id = (
<select>id</select>
<from>facedetails</from>
<where>id like 34 group by id)</where>
</where>
</SQLStatement>
Related
I need to select records from an MS Access database to an XML output, based on some predefined conditions, from my Java application using JDBC & SQL statements.
Is there a way to achieve that?
Access SQL does not have an equivalent to T-SQL's FOR XML clause. However, you can add a class like this to your project
package com.example.ucanaccessdemo;
import java.io.StringWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 ResultSetToXml {
// adapted from
// http://www.java2s.com/Code/Java/Database-SQL-JDBC/ConvertaResultSettoXML.htm
public static String asXml(ResultSet rs) throws ParserConfigurationException, SQLException, TransformerException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element results = doc.createElement("Results");
doc.appendChild(results);
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
while (rs.next()) {
Element row = doc.createElement("Row");
results.appendChild(row);
for (int i = 1; i <= colCount; i++) {
String columnName = rsmd.getColumnName(i);
Object value = rs.getObject(i);
if (value != null) {
Element node = doc.createElement(columnName);
node.appendChild(doc.createTextNode(value.toString()));
row.appendChild(node);
}
}
}
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
return sw.toString();
}
}
and then pass your ResultSet to the asXml method
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Clients");
String xml = ResultSetToXml.asXml(rs);
For a sample table like this ...
ID LastName FirstName DOB
-- ------------ --------- -------------------
1 Thompson Gord 2017-04-01 07:06:27
2 Loblaw Bob 1966-09-12 16:03:00
3 Παπαδόπουλος Ώπα
... the resulting xml string will look like this (formatted for readability)
<Results>
<Row>
<ID>1</ID>
<LastName>Thompson</LastName>
<FirstName>Gord</FirstName>
<DOB>2017-04-01 07:06:27.0</DOB>
</Row>
<Row>
<ID>2</ID>
<LastName>Loblaw</LastName>
<FirstName>Bob</FirstName>
<DOB>1966-09-12 16:03:00.0</DOB>
</Row>
<Row>
<ID>3</ID>
<LastName>Παπαδόπουλος</LastName>
<FirstName>Ώπα</FirstName>
</Row>
</Results>
This is my first post on Stack, so if there is something wrong, be patient ...
Ok, my question is how can I write an XML attribute with value. The result would be something like this:
<GroupAttribute>
<Attribute name = "Color"> Pink </Attribute>
.....
</GroupAttribute>
I tried this:
Element attribute = doc.createElement ("attribute");
groupAttribute.appendChild (attribute);
attribute.setAttribute ("attributeType" p.attributeColor);
groupAttribute.appendChild (getCompanyElements (doc, attribute, "attribute", p.attributeColor));
But it does not work.. the result is:
<GroupAttribute>
<Attribute> Pink </Attribute>
.....
</GroupAttribute>
the setAttribute is missing ...
What am I doing wrong?
Here the code:
import com.opencsv.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
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 org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
*
* #author Mike
*/
public class prueba {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
List<Producto> prods = new ArrayList<Producto>();
try {
CSVReader reader;
reader = new CSVReader(new FileReader("C:\\Temp\\feeds\\Product_Prueba.csv"), ';');
String[] nextLine;
try {
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
//System.out.println(Arrays.toString(nextLine));
//Lee
Producto p;
p = new Producto();
p.attributeColor = "Pink";
prods.add(p);
}
} catch (IOException ex) {
Logger.getLogger(prueba.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(prueba.class.getName()).log(Level.SEVERE, null, ex);
}
xeraXML(prods);
}
static void xeraXML(List<Producto> ps) {
DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder icBuilder;
try {
icBuilder = icFactory.newDocumentBuilder();
Document doc = icBuilder.newDocument();
Element mainRootElement = doc.createElement("productRequest");
doc.appendChild(mainRootElement);
for (Iterator<Producto> i = ps.iterator(); i.hasNext();) {
Producto p;
p = i.next();
mainRootElement.appendChild(getProductElement(doc, p));
}
// output DOM XML to console
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult console = new StreamResult(System.out);
//StreamResult out = new StreamResult("C:\\Temp\\results\\resultado.xml");
transformer.transform(source, console);
//transformer.transform(source, out);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Element getProductElement(Document doc /*String localizedFor,*/, Producto p) {
Element groupAttribute = doc.createElement("groupAttribute");
Element attribute = doc.createElement("attribute");
groupAttribute.appendChild(attribute);
attribute.setAttribute("attributeType", p.attributeColor);
groupAttribute.appendChild(getElements(doc, attribute, "attribute", p.attributeColor));
return groupAttribute;
}
private static Node getElements(Document doc, Element element, String name, String value) {
Element node = doc.createElement(name);
node.appendChild(doc.createTextNode(value));
return node;
}
}
And here the Producto class:
public class Producto {
public String attributeColor;
}
I just wanted to add the comment but am writing it as an answer since I don't have that privilege yet. I was looking to add the attribute to the xml node and I came across this post.
dependency = dom.createElement("dependency");
dependency.setAttribute("type", "value");
dependencies.appendChild(dependency);
I added the child after setting the attribute.
I'm creating an XML using DOM, I open the XML with explorer and it seems fine.
After that I created an XSL for it, add the reference to it programatically to the XML and boom, it works no longer.
I inspect the code in the browser and save the file as XML.
I open the XML with notepad++ and noticed the npp shows the XML file is encoded in "UCS-2 LE BOM" even though the XML header sais it's in "UTF-8", I don't know if this has to do with being saved from the browser or it's because of Java transformer.File encoding according to npp
Anyway, I change the file encoding in npp to "UTF-8", open it again and it works flawlessly.
I've tried changing the transformer's encoding property transformer.setOutputProperty("encoding", "ISO-8859-1") to different values but it will just change the XML header.
I googled around but I haven't found anything that's worked so far.
This is the code where the XML is created
package modelo;
import java.awt.Desktop;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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.w3c.dom.Node;
public class DAOXML {
private static final String rutaUno = ".\\VerLibro.xml";
private static final String rutaListado = ".\\listado.xml";
public static boolean toXML(ArrayList<Libro> libros2) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
final String rutaActual = libros2.size()>1?rutaListado:rutaUno;
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
doc.setDocumentURI(rutaActual);
doc.setXmlStandalone(true);
Element libros = doc.createElement("libros");
for(Libro l : libros2) {
Element libro = doc.createElement("libro");
Element isbn = doc.createElement("isbn");
isbn.setTextContent(l.getISBN());
libro.appendChild(isbn);
Element editorial = doc.createElement("editorial_apellidos");
editorial.setTextContent(l.getEditorial_apellidos());
libro.appendChild(editorial);
Element autor = doc.createElement("autor");
autor.setTextContent(l.getAutor());
libro.appendChild(autor);
Element categoria = doc.createElement("categoria");
categoria.setTextContent(l.getCategoria());
libro.appendChild(categoria);
Element titulo = doc.createElement("titulo");
titulo.setTextContent(l.getTitulo());
libro.appendChild(titulo);
Element ubicacion = doc.createElement("ubicacion");
ubicacion.setTextContent(l.getUbiacion());
libro.appendChild(ubicacion);
libros.appendChild(libro);
}
doc.appendChild(libros);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// transformer.setOutputProperty("encoding", "ISO-8859-1");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(rutaActual));
//result.setWriter(new PrintWriter(new File(rutaActual), "UTF-8"));
transformer.transform(source, result);
if(rutaActual == rutaUno) {
Node pi = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"VerLibro.xsl\"");
doc.insertBefore(pi, libros);
}
else {
Node pi = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"listado.xsl\"");
doc.insertBefore(pi, libros);
}
Desktop.getDesktop().open(new File(rutaActual));
return true;
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
Thanks in advance.
Try adding this line before you call transform():
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
I have a problem in parsing xml files with xslt stylesheets
http://docs.oracle.com/javase/tutorial/jaxp/xslt/transformingXML.html
i changed a bit in the stylizer code to input more than one xml file
(( just to give you a good background ))
everything is working perfectly BUT the root is mutiplied !
this is my xsl code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl" version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:text>
</xsl:text>
<request campus="UQU" year="2013" term="second">
<xsl:for-each select="/SIS_REP070/LIST_G_STUDENT_ID/G_STUDENT_ID">
.
.
.
<xsl:for-each select="document('sis_rep413b_anon.xml')/MODULE1/LIST_G_STUDENT_ID/G_STUDENT_ID[STUDENT_ID=$varID]">
.
.
.
<xsl:for-each select="document('sis_rep814.xml')/SIS_REP814/LIST_DEGREE_PLANS/DEGREE_PLANS[EDITION1=57][TOTAL_HRS=160]/LIST_G_COURSE_LEVEL/G_COURSE_LEVEL/LIST_G_COURSE_CODE/G_COURSE_CODE">
.
.
.
</xsl:for-each>
</request>
</xsl:template>
</xsl:stylesheet>
As you can see i am implementing this stylesheet on several xmls
so the root is outputed x times ( x= xml input files )
this is what the output looks like :
<request campus="UQU" year="2013" term="second">
<student key="42701646">
<name first="فؤاد" last="خوج"/><MAX>0</MAX>
<acadArea abbv="CSandISG"><major code="143100"/></acadArea>
<updateCourseRequests commit="true">
<courseOffering1 subjectArea="RELg" courseNumber="16312012" priority="19981.921" credit="2"/>
</updateCourseRequests></student>
.
.
.
.
</request>
<request campus="UQU" year="2013" term="second"/>
<request campus="UQU" year="2013" term="second"/>
<request campus="UQU" year="2013" term="second"/>
The root "request" is printed three more times !:(
Because i entered four xml files
This is the command i wrote in the command prompt :
java Stylizer data/file1.xsl data/file1.xml data/file2.xml data/file3.xml data/file4.xml
THE ORIGINAL STYLIZER:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
// For write operation
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
public class Stylizer {
// Global value so it can be ref'd by the tree-adapter
static Document document;
public static void main(String[] argv) {
if (argv.length != 2) {
System.err.println("Usage: java Stylizer stylesheet xmlfile");
System.exit(1);
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//factory.setNamespaceAware(true);
//factory.setValidating(true);
try {
File stylesheet = new File(argv[0]);
File datafile = new File(argv[1]);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(datafile);
// Use a Transformer for output
TransformerFactory tFactory = TransformerFactory.newInstance();
StreamSource stylesource = new StreamSource(stylesheet);
Transformer transformer = tFactory.newTransformer(stylesource);
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
} catch (TransformerConfigurationException tce) {
// Error generated by the parser
System.out.println("\n** Transformer Factory error");
System.out.println(" " + tce.getMessage());
// Use the contained exception, if any
Throwable x = tce;
if (tce.getException() != null) {
x = tce.getException();
}
x.printStackTrace();
} catch (TransformerException te) {
// Error generated by the parser
System.out.println("\n** Transformation error");
System.out.println(" " + te.getMessage());
// Use the contained exception, if any
Throwable x = te;
if (te.getException() != null) {
x = te.getException();
}
x.printStackTrace();
} catch (SAXException sxe) {
// Error generated by this application
// (or a parser-initialization error)
Exception x = sxe;
if (sxe.getException() != null) {
x = sxe.getException();
}
x.printStackTrace();
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
}
} // main
}
AFTER MY MODIFICATION :
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
// For write operation
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
public class Stylizer {
public static void main(String[] argv) {
if (argv.length < 2) {
System.err.println("Usage: java Stylizer stylesheet xmlfile");
System.exit(1);
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//factory.setNamespaceAware(true);
//factory.setValidating(true);
try {
File stylesheet = new File(argv[0]);
File [] fileList = new File[argv.length];
for(int i=1 ; i<argv.length ; i++)
fileList[i] = new File(argv[i]);
String targetExtension = ".xml";
int extIndex = argv[0].lastIndexOf(".");
String ext = argv[0].substring(extIndex);
argv[0] = argv[0].substring(0, extIndex) + targetExtension;
File outputname = new File(argv[0]);
DocumentBuilder builder = factory.newDocumentBuilder();
Document [] document = new Document[argv.length];
for(int i=1 ; i<argv.length ; i++)
document[i] = builder.parse(fileList[i]);
// Use a Transformer for output
TransformerFactory tFactory = TransformerFactory.newInstance();
StreamSource stylesource = new StreamSource(stylesheet);
Transformer transformer = tFactory.newTransformer(stylesource);
DOMSource [] source = new DOMSource [argv.length];
for(int i=1 ; i<argv.length ; i++)
source[i] = new DOMSource(document[i]);
FileOutputStream outputStream = new FileOutputStream((File)outputname);
StreamResult result = new StreamResult(outputStream);
for(int i=1 ; i<argv.length ; i++)
transformer.transform(source[i], result);
} catch (TransformerConfigurationException tce) {
// Error generated by the parser
System.out.println("\n** Transformer Factory error");
System.out.println(" " + tce.getMessage());
// Use the contained exception, if any
Throwable x = tce;
if (tce.getException() != null) {
x = tce.getException();
}
x.printStackTrace();
} catch (TransformerException te) {
// Error generated by the parser
System.out.println("\n** Transformation error");
System.out.println(" " + te.getMessage());
// Use the contained exception, if any
Throwable x = te;
if (te.getException() != null) {
x = te.getException();
}
x.printStackTrace();
} catch (SAXException sxe) {
// Error generated by this application
// (or a parser-initialization error)
Exception x = sxe;
if (sxe.getException() != null) {
x = sxe.getException();
}
x.printStackTrace();
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
}
} // main
}
You create a new file outputname by changing the name of the stylesheet file to end in .xml.
You use this file for a new FileOutputStream called outputStream.
Then you use this output stream for a new StreamResult called result.
Finally you transform each of your source XML files using the same result stream.
The transformer is doing as you have told it: it is transforming each DOM source independently and putting the results of each one in the same place.
It's not clear what you expect. Do you want the output combined into a single XML document somehow? If so then you must say how you want them combined.
Are you using four command-line XML files as well as the other two XML files that are in document calls in the XSLT stylesheet? Six XML files to be combined into one is an awful lot!
If you want four independent transforms then you will have to create four different output files and send the output of each transform to a different place.
I have a folder with some stock price files in the form stockA.txt
I am trying to create a java program that stores the filename without the extension in an xml file as a node.
For example the file.xml should be in the form :
<stockA></stockA>
<stockB></stockB>
The problem is that I am getting the following error code :
Exception in thread "main" org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
Here is the code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package xmlfilecreation;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
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;
/**
*
* #author Administrator
*/
public class XMLFileCreation {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
File folder = new File("/Users/Administrator/Documents/TM470/NYSE_EOD/NyseLast2Years/");
File[] listOfFiles = folder.listFiles();
List<String> results = new ArrayList<String>();
for (int i = 0; i < listOfFiles.length; i++)
{
results.add(listOfFiles[i].getName().replace(".txt", ""));
//System.out.println(results.get(i));
}
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
//elements
Document doc = docBuilder.newDocument();
//root element
Element rootElement = doc.createElement("Stocks");
doc.appendChild(rootElement);
int counter = 0;
Element myElement;
for (String item: results)
{
myElement = doc.createElement(item);
doc.appendChild(myElement);
rootElement.appendChild(myElement);
counter++;
}
System.out.println(counter);
//write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("file.xml"));
transformer.transform(source, result);
System.out.println("File saved!");
}
catch (ParserConfigurationException ex)
{
ex.printStackTrace();
}
catch(TransformerException ex)
{
ex.printStackTrace();
}
}
}
How can I fix that error?
Thank you.
You're appending twice the elements, one time at root level, and the other one in the Stocks tag. You just need to do it only once.
for (String item: results) {
Element myElement = doc.createElement(item);
// doc.appendChild(myElement); -> You don't need this one
rootElement.appendChild(myElement);
counter++;
}
Appending to the root element does suffice.