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.
Related
I have the following source XML file named customers.xml:
<?xml version="1.0" encoding="utf-8"?>
<p:CustomerElement xmlns:p="http://www.dog.com/customer" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:schemaLocation="http://www.dog.com/customer Customer.xsd">
<Customer>
<Sender>
<transmitDate>2016-02-21T00:00:00</transmitDate>
<transmitter>Dog ETL v2.0</transmitter>
<dealerCode><![CDATA[P020]]></dealerCode>
<DMSSystem><![CDATA[DBS]]></DMSSystem>
<DMSReleaseNumber><![CDATA[5.0]]></DMSReleaseNumber>
</Sender>
<Identifier>
<updateInd><![CDATA[A]]></updateInd>
<dealerCustNumber><![CDATA[AMADOR]]></dealerCustNumber>
<dealerCustName><![CDATA[AMADOR COMPUTERS]]></dealerCustName>
<phoneNumber><![CDATA[800 111 4444]]></phoneNumber>
<faxNumber><![CDATA[780 111 4444]]></faxNumber>
<email xsi:nil="true" />
<customerType><![CDATA[R]]></customerType>
<activeCustomerInd>false</activeCustomerInd>
<parentCustomerNumber xsi:nil="true" />
<primaryStoreNumber><![CDATA[00]]></primaryStoreNumber>
<preferredLanguage><![CDATA[ENG]]></preferredLanguage>
<dealerDateInSystem>2000-01-11T00:00:00</dealerDateInSystem>
<dealerLastUpdatedDate>2015-02-05T00:00:00</dealerLastUpdatedDate>
</Identifier>
<Location>
<address2><![CDATA[ACCOUNT FLAGGED FOR DELETION]]></address2>
<address3><![CDATA[AS PER BILL FEB AA/15]]></address3>
<city><![CDATA[CHICAGO]]></city>
<postalCode><![CDATA[Q5S 1E5]]></postalCode>
<state><![CDATA[AB]]></state>
<country><![CDATA[CA]]></country>
<location><![CDATA[FLAGGED FOR DELETION]]></location>
<addressType><![CDATA[M]]></addressType>
</Location>
<Division>
<divisionCode><![CDATA[G]]></divisionCode>
<divisionName><![CDATA[CAR]]></divisionName>
<IndustryCode>
<industryCode><![CDATA[AQ99]]></industryCode>
<primaryIndustryCodeInd>true</primaryIndustryCodeInd>
</IndustryCode>
<SalesRep>
<number><![CDATA[XXX]]></number>
<name><![CDATA[KILL ACCOUNT IN PROCESS]]></name>
<type><![CDATA[M]]></type>
<par>0</par>
<email xsi:nil="true" />
<phoneNumber><![CDATA[000 000 0000]]></phoneNumber>
</SalesRep>
</Division>
</Customer>
<Customer>
<Sender>
<transmitDate>2016-02-21T00:00:00</transmitDate>
<transmitter>Dog ETL v2.0</transmitter>
<dealerCode><![CDATA[P000]]></dealerCode>
<DMSSystem><![CDATA[DBS]]></DMSSystem>
<DMSReleaseNumber><![CDATA[5.0]]></DMSReleaseNumber>
</Sender>
<Identifier>
<updateInd><![CDATA[A]]></updateInd>
<dealerCustNumber><![CDATA[UU20888]]></dealerCustNumber>
<dealerCustName><![CDATA[ ADVERTISING AND PR]]></dealerCustName>
<phoneNumber xsi:nil="true" />
<faxNumber xsi:nil="true" />
<email xsi:nil="true" />
<customerType><![CDATA[I]]></customerType>
<activeCustomerInd>true</activeCustomerInd>
<parentCustomerNumber xsi:nil="true" />
<primaryStoreNumber><![CDATA[M2]]></primaryStoreNumber>
<preferredLanguage><![CDATA[ENG]]></preferredLanguage>
<dealerDateInSystem>2015-11-18T00:00:00</dealerDateInSystem>
<dealerLastUpdatedDate>2015-11-19T00:00:00</dealerLastUpdatedDate>
</Identifier>
<Location>
<address2><![CDATA[EQUIP]]></address2>
<city><![CDATA[ADER]]></city>
<country><![CDATA[CA]]></country>
<addressType><![CDATA[M]]></addressType>
</Location>
<Division>
<divisionCode><![CDATA[A]]></divisionCode>
<divisionName><![CDATA[AGRO]]></divisionName>
<IndustryCode>
<industryCode><![CDATA[EQ00]]></industryCode>
<primaryIndustryCodeInd>true</primaryIndustryCodeInd>
</IndustryCode>
</Division>
</Customer>
</p:CustomerElement>
I have the following java code, which parses customers.xml into individual "Customer" entities, and then attempts to convert each of them into an AVRO format:
package com.dogsoft.data.xmltoavro;
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
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 jdk.nashorn.internal.runtime.regexp.joni.constants.NodeType;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.apache.avro.Protocol;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.avro.util.Utf8;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
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 java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
public class ParseXmlFile {
private static Protocol protocol;
public static void xmlToAvro(File xmlFile, File avroFile) throws IOException, SAXException {
try {
InputStream stream = new FileInputStream("/tmp/xml.avsc");
if (stream == null) throw new IllegalStateException("Classpath should include xml.avsc");
protocol = Protocol.parse(stream);
} catch (IOException e) {
throw new RuntimeException(e);
}
Schema schema = protocol.getType("Element");
Document doc = parse(xmlFile);
DatumWriter<GenericRecord> datumWriter = new SpecificDatumWriter<>(schema);
try (DataFileWriter<GenericRecord> fileWriter = new DataFileWriter<>(datumWriter)) {
fileWriter.create(schema, avroFile);
Object docElement = doc.getDocumentElement();
fileWriter.append(wrapElement(doc.getDocumentElement()));
}
}
private static GenericData.Record wrapElement(Element el) {
GenericData.Record record = new GenericData.Record(protocol.getType("Element"));
record.put("name", el.getNodeName());
NamedNodeMap attributeNodes = el.getAttributes();
List<GenericData.Record> attrRecords = new ArrayList<>();
for (int i = 0; i < attributeNodes.getLength(); i++) {
Attr attr = (Attr) attributeNodes.item(i);
attrRecords.add(wrapAttr(attr));
}
record.put("attributes", attrRecords);
List<Object> childArray = new ArrayList<>();
NodeList childNodes = el.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
Object nt = node.getNodeType();
if (node.getNodeType() == Node.ELEMENT_NODE)
childArray.add(wrapElement((Element) node));
if (node.getNodeType() == Node.TEXT_NODE)
childArray.add(node.getTextContent());
}
record.put("children", childArray);
return record;
}
private static GenericData.Record wrapAttr(Attr attr) {
GenericData.Record record = new GenericData.Record(protocol.getType("Attribute"));
record.put("name", attr.getName());
record.put("value", attr.getValue());
return record;
}
private static Document parse(File file) throws IOException, SAXException {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return builder.parse(file);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
}
public static void avroToXml(File avroFile, File xmlFile) throws IOException {
try {
InputStream stream = new FileInputStream("/tmp/xml.avsc");
if (stream == null) throw new IllegalStateException("Classpath should include xml.avsc");
protocol = Protocol.parse(stream);
} catch (IOException e) {
throw new RuntimeException(e);
}
DatumReader<GenericRecord> datumReader = new GenericDatumReader<>(protocol.getType("Element"));
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<>(avroFile, datumReader);
GenericRecord record = dataFileReader.next();
Document doc;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
Element el = unwrapElement(record, doc);
doc.appendChild(el);
saveDocument(doc, xmlFile);
}
private static Element unwrapElement(GenericRecord record, Document doc) {
String name = "" + record.get("name");
Element el = doc.createElement(name);
#SuppressWarnings("unchecked")
GenericArray<GenericRecord> attrArray = (GenericArray<GenericRecord>) record.get("attributes");
for (GenericRecord attrRecord : attrArray)
el.setAttributeNode(unwrapAttr(attrRecord, doc));
#SuppressWarnings("unchecked")
GenericArray<Object> childArray = (GenericArray<Object>) record.get("children");
for (Object childObj : childArray) {
if (childObj instanceof GenericRecord)
el.appendChild(unwrapElement((GenericRecord) childObj, doc));
if (childObj instanceof Utf8)
el.appendChild(doc.createTextNode("" + childObj));
}
return el;
}
private static Attr unwrapAttr(GenericRecord record, Document doc) {
Attr attr = doc.createAttribute("" + record.get("name"));
attr.setValue("" + record.get("value"));
return attr;
}
private static void saveDocument(Document doc, File file) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(file));
} catch (TransformerException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args)
{
Object nodeObject = null;
Node myNode = null;
Transformer transformer = null;
try
{
try {
transformer =
TransformerFactory.newInstance().newTransformer();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("/tmp/customers.xml");
System.out.printf("Version = %s%n", doc.getXmlVersion());
System.out.printf("Encoding = %s%n", doc.getXmlEncoding());
System.out.printf("Standalone = %b%n%n", doc.getXmlStandalone());
if (doc.hasChildNodes())
{
int customerNumber = 0;
NodeList nl = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(node.toString());
customerNumber++;
File avroFile = new File("/tmp/customer" + customerNumber + ".avro");
File xmlFile = new File("/tmp/customer" + customerNumber + ".xml");
File xmlFile1 = new File("/tmp/customer" + customerNumber + "-foo.xml");
try {
transformer.transform(
new DOMSource(node), new StreamResult(xmlFile));
File outputFile = new File("/tmp/customer" + customerNumber + ".avro");
xmlToAvro(xmlFile, outputFile);
} catch (TransformerException e) {
e.printStackTrace();
}
}
}
}
}
catch (IOException ioe)
{
System.err.println("IOE: " + ioe);
}
catch (SAXException saxe)
{
System.err.println("SAXE: " + saxe);
}
catch (FactoryConfigurationError fce)
{
System.err.println("FCE: " + fce);
}
catch (ParserConfigurationException pce)
{
System.err.println("PCE: " + pce);
}
}
}
This code works overall, but it ignores any content, which is enclosed into
![CDATA[
tag. As it happens, most of the actual useful data in the customers.xml files is enclosed into these tags.
Is there a way to modify this code, to make it not ignore the CDATA contents?
Instead of hand-writing parser code, you might want to split the problem in two parts: first, bind XML into POJO (using JAXB or Jackson XML module); and then write POJO as Avro (using Apache Avro lib, or Jackson Avro module). All you need for that would be POJO definition that matches expected structure for data as XML and Avro. Result should be less code, and basically specifying what needs to happen and now how to do it.
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 made a method to read XML files, but now I need to write or override that same XML file with the same tags, nodes and objects, but with different data inside child nodes.
First I want to make read and write working and then I have some ideas to maybe put the whole XML file into a buffer. Then I could put the whole XML under one class and just write that class again into the same XML this is just an idea, any suggestion or idea is welcome.
My XML file looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Document Root -->
<DATA>
<Settings USERNAME="test" PASSWORD="test" STATUS="active" / >
</DATA>
This is my code for reading:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class Read {
private final static String SETTINGS_LINE = Settings;
public void readXML() {
try {
File xmlFile = new File("Test.xml");
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(xmlFile);
// Normalize the XML file
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for(int temp = 0; temp < nodeList.getLength(); temp++) {
Node node = nodeList.item(temp);
if(node instanceof Element && node.getNodeName() == SETTINGS_LINE) {
Element settings = (Element) node;
System.out.println("User" +settings.getAttribute("USERNAME"));
System.out.println("Password" +settings.getAttribute("PASSWORD"));
System.out.println("Status" +settings.getAttribute("STATUS"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
And this is the code for writing that is not working:
import java.io.File;
import java.io.IOException;
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.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Modify {
private final static String SETTINGS_LINE = "Settings";
public static void main(String argv[]) {
try {
String filepath = "test.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// Normalize the XML File
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element && node.getNodeName() == SETTINGS_LINE) {
Element settings = (Element) node;
if("USERNAME".equals(node.getChildNodes())){
node.setTextContent("mivnadic");
}
}
// 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(filepath));
transformer.transform(source, result);
}
System.out.println("File saved");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}
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>
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.