Magazine
 
JAXP API using DOM Parser
//Create transformer
Transformer tFormer =
TransformerFactory.newInstance().newTransformer();
// Output text type
tFormer.setOutputProperty(OutputKeys.METHOD,
“text”);
//Write the document to a file
Source source = new
DOMSource(doc);
Result result = new
StreamResult(System.out);
tFormer.transform(source, result);

The setOutputProperty method of the Transformer class set the output key as a text to print the data on console. Then the transform() method displays the data source
and the given destination. This program uses the “System.out” to display the data on the console.

Here is full source code of GetDomData.java:

 

import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import
javax.xml.transform.stream.StreamResult;
public class GetDomData{
static public void main(String[] arg) {
try{
BufferedReader bf = new
BufferedReader(new
InputStreamReader(System.in));
System.out.print(“Enter XML file name:
“);
String xmlFile = bf.readLine();
File file = new File(xmlFile);
if (file.exists()){
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =
factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
System.out.println(xmlFile + “ is wellformed
“);
 

NodeList list =
doc.getElementsByTagName(“*”);
for (int i=0; i<list.getLength(); i++){
// Get element
Element element =
(Element)list.item(i);
//Source src = new
DOMSource(element);
System.out.println(element.getNodeName());
} // Create transformer
Transformer tFormer =
TransformerFactory.newInstance().newTransformer();
// Output text type
tFormer.setOutputProperty(OutputKeys.METHOD,
“text”);
// Write the document to a file
Source source = new DOMSource(doc);
Result result = new
StreamResult(System.out);
tFormer.transform(source, result);
}
else{
System.out.println(“File not found!”);
}
}
catch (Exception e){
System.err.println(e);
System.exit(0);
}
}
}

Output of the Program:

C:\nisha>javac GetDomData.java
C:\nisha>java GetDomData
Enter XML file name: emp.xml
emp.xml is well-formed
Employee-Detail
Employee
Emp_Id
Emp_Name
Emp_E-mail
Employee
Emp_Id
Emp_Name

     
Mar 2008 | Java Jazz Up |22
 
previous
index
next
 
View All Topics
All Pages of this Issue
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59,

Download PDF