Magazine
 
JAXP API using DOM Parser
aTransformer.transform(src, dest);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}

The given code will generate the following xml code and display on the console.

<?xml version=”1.0" encoding=”UTF-8"
standalone=”no”?>
<root>
<!—This is comment—>
<Child attribute1=”The value of Attribute 1"/
>
</root>

Download the Program

Lets see another example that helps you to retrieve the elements as well as their corresponding data from the DOM tree. In this example you need a well-formed XML
file that has some data (Emp_Id, Emp_Name and Emp_E-mail in our case).

Here is the XML File (emp.xml) to be parsed:

<?xml version = “1.0” ?>
<Employee-Detail>
<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod </Emp_Name>
<Emp_E-mail> Vinod1@yahoo.com </
Emp_E-mail>
</Employee>
<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit </Emp_Name>
<Emp_E-mail> Amit2@yahoo.com </Emp_Email>
</Employee>
<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak </Emp_Name>
<Emp_E-mail> Deepak3@yahoo.com </
Emp_E-mail>
</Employee>
</Employee-Detail>
 

Develop a java file (GetDomData.java) that uses an xml file to parse. Initially the program checks that the given file exists or not by using exists() method. It determines that the parsed xml is well formed or not. If you enter a file
that doesn’t exist it will show “File not found!”.

Here is a sample code of this program:

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
“);

To parse the xml file you need the DoucnemtBuilderFactory and DocumentBuilder. The object of the DocumentBuilder uses parse method and determines that the parsed xml is well formed or not. If xml document is willformed, it will display a message “emp.xml is well-formed!” Otherwise prints “emp.xml isn’t
well-formed!”.

Now, lets see the sample code to retrieve the elements from the xml file:

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());
}

The doc object helps in create a NodeList through the getElementByTagName() method. The NodeList helps you in getting the length and Element. For getting the node name you use the getNodeName() method.

Now, lets see the sample code to retrieve the data from the elements:

Mar   2008 | Java Jazz Up |21
 
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