01.
import javax.xml.parsers.DocumentBuilderFactory;
02.
import javax.xml.parsers.DocumentBuilder;
03.
import org.w3c.dom.Document;
04.
import org.w3c.dom.Element;
05.
import org.w3c.dom.DOMException;
06.
import org.w3c.dom.Node;
07.
import org.w3c.dom.NodeList;
08.
import java.io.IOException;
09.
import java.io.File;
10.
import javax.swing.JOptionPane;
11.
12.
public class DOMRead1 {
13.
14.
15.
public static void main(String[] args) {
16.
String filename=
"customers.xml"
;
17.
String output=
""
;
18.
try
{
19.
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
20.
DocumentBuilder parser=factory.newDocumentBuilder();
21.
Document doc=parser.parse(
new
File(filename));
22.
Element root=doc.getDocumentElement();
23.
NodeList customerList=root.getElementsByTagName(
"customer"
);
24.
Element emCustomer,temp;
25.
Node node;
26.
for
(int i=0;i<customerList.getLength();i++){
27.
28.
emCustomer=(Element)customerList.item(i);
29.
temp=(Element)emCustomer.getElementsByTagName(
"customer"
).item(0);
30.
output+=
"customer:"
+temp.getAttribute(
"id"
)+
"\n"
;
31.
32.
node=temp.getElementsByTagName(
"Mr"
).item(0);
33.
output+=temp.getTagName()+
"\n"
;
34.
35.
NodeList profileList=temp.getElementsByTagName(
"profile"
);
36.
for
(int j=0;j<profileList.getLength();j++){
37.
node=profileList.item(j);
38.
output+=node.getNodeName()+
":"
+node.getFirstChild().getNodeValue()+
"\n"
;
39.
}
40.
node=temp.getElementsByTagName(
"occupation"
).item(0);
41.
output+=
"Occupation:"
+node.getFirstChild().getNodeValue()+
"\n"
;
42.
43.
temp=(Element)emCustomer.getElementsByTagName(
"birthplace"
).item(0);
44.
output+=
"Country:"
+temp.getAttribute(
"county"
)+
"\n"
;
45.
node=temp.getElementsByTagName(
"birthplace"
).item(0);
46.
output+=
"Birthplace:"
+node.getFirstChild().getNodeValue()+
"\n"
;
47.
output+=
"\n"
;
48.
49.
}
50.
JOptionPane.showMessageDialog(
null
, output);
51.
52.
}
53.
catch
(DOMException d){
54.
d.printStackTrace();
55.
}
56.
catch
(IOException io){
57.
io.printStackTrace();
58.
}
59.
catch
(Exception e){
60.
e.printStackTrace();
61.
}
62.
63.
64.
65.
66.
}
67.
68.
}