Tuesday, May 19, 2009

Creating XML Document using DOM

更多精彩请到 http://www.139ya.com

From : http://www.javareference.com/jrexamples/viewexample.jsp?id=63

Creating XML Document using DOM
[ contributed by Darshan Singh ]
bookmark this on del.icio.us Discuss this Example with Darshan Singh
Print E-Mail
Description:
This example reads a CSV file and creates an XML document from it. The first line in the CSV file is assumed to be the field/column names, and these names are used as element names in the XML document. Like in previous example, DocumentBuilderFactory is used to create an instance of DocumentBuilder class. This time we call newDocument method on DocumentBuilder. This method returns an instance of org.w3c.dom.Document class that is then used to create XML document by calling methods such as createElement and appendChild.


Example Code:
The main function creates an instance of CSV2XML class and calls convertFile method. This method starts reading the CSV file. It uses stringTokenizer to first get the column names (from the first row) and then the actual data items (for each row starting second row in the file) and creates XML elements.
The below code uses JAXP classes TransformerFactory and Transformer to save the document. The alternative approach would be to use org.apache.crimson.tree.XmlDocument class as below:

BufferedWriter bufferWriter = new BufferedWriter(new FileWriter(xmlFileName));

XmlDocument xDoc = (XmlDocument)newDoc;
xDoc.write(bufferWriter);

bufferWriter.close();"



/**
* DOM Example: Creating XML document by converting CSV file to XML
* First line in CSV file is field/column names -
* which is also used as element names while creating XML document
*/
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class CSV2XML {

// Protected Properties
protected DocumentBuilderFactory domFactory = null;
protected DocumentBuilder domBuilder = null;

// CTOR
public CSV2XML()
{
try
{
domFactory = DocumentBuilderFactory.newInstance();
domBuilder = domFactory.newDocumentBuilder();
}
catch(FactoryConfigurationError exp)
{
System.err.println(exp.toString());
}
catch(ParserConfigurationException exp)
{
System.err.println(exp.toString());
}
catch(Exception exp)
{
System.err.println(exp.toString());
}
}

public int convertFile(String csvFileName, String xmlFileName)
{
int rowsCount = -1;
try
{
Document newDoc = domBuilder.newDocument();

// Root element
Element rootElement = newDoc.createElement("CSV2XML");
newDoc.appendChild(rootElement);

// Read comma seperated file
BufferedReader csvReader;
csvReader = new BufferedReader(new FileReader(csvFileName));
int fieldCount = 0;
String[] csvFields = null;
StringTokenizer stringTokenizer = null;

// Assumption: first line in CSV file is column/field names
// As the column names are used to name the elements in the XML file,
// avoid using spaces/any other characters not suitable for XML element naming
String curLine = csvReader.readLine();
if(curLine != null)
{
stringTokenizer = new StringTokenizer(curLine, ",");
fieldCount = stringTokenizer.countTokens();
if(fieldCount > 0)
{
csvFields = new String[fieldCount];
int i=0;
while(stringTokenizer.hasMoreElements())
csvFields[i++] = String.valueOf(stringTokenizer.nextElement());
}
}

// Now we know the columns, now read data row lines
while((curLine = csvReader.readLine()) != null)
{
stringTokenizer = new StringTokenizer(curLine, ",");
fieldCount = stringTokenizer.countTokens();

if(fieldCount > 0)
{
Element rowElement = newDoc.createElement("row");

int i=0;
while(stringTokenizer.hasMoreElements())
{
try
{
String curValue = String.valueOf(stringTokenizer.nextElement());
Element curElement = newDoc.createElement(csvFields[i++]);
curElement.appendChild(newDoc.createTextNode(curValue));
rowElement.appendChild(curElement);
}
catch(Exception exp)
{
}
}

rootElement.appendChild(rowElement);
rowsCount++;
}

}

csvReader.close();

// Save the document to the disk file
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();

Source src = new DOMSource(newDoc);
Result dest = new StreamResult(new File(xmlFileName));
aTransformer.transform(src, dest);

rowsCount++;
}
catch(IOException exp)
{
System.err.println(exp.toString());
}
catch(Exception exp)
{
System.err.println(exp.toString());
}

return rowsCount;
}

public static void main(String[] args)
{
try
{
if(args.length != 2)
{
System.out.println("Usage: java CSV2XML ");
return;
}
}
catch(Exception exp)
{
System.err.println(exp.toString());
}

try
{
CSV2XML csvConverter = new CSV2XML();
int rowsCount = csvConverter.convertFile(args[0], args[1]);

if(rowsCount >= 0)
{
System.out.println("CSV File " + args[0] +
"' successfully converted to XML File "+ args[1] + "\n" +
"(" + String.valueOf(rowsCount) + " rows)");
}
else
{
System.out.println("Error while converting input CSV File " + args[0] +
" to output XML File "+ args[1] + " ");
}
}
catch(Exception exp)
{
System.err.println(exp.toString());
}
}
}

No comments: