1String dir = System.getProperty("user.dir");
2File inputFile = new File(dir + File.separator + "dats.xml");
3DocumentBuilderFactory dbFactory =
4 DocumentBuilderFactory.newInstance();
5DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
6Document doc = dBuilder.parse(inputFile);
7doc.getDocumentElement().normalize();
8/*
9Elimina nodos vacíos y combina adyacentes en caso de que los
10hubiera
11*/
1
2package com.mkyong.seo;
3
4import javax.xml.parsers.DocumentBuilderFactory;
5import javax.xml.parsers.DocumentBuilder;
6import org.w3c.dom.Document;
7import org.w3c.dom.NodeList;
8import org.w3c.dom.Node;
9import org.w3c.dom.Element;
10import java.io.File;
11
12public class ReadXMLFile {
13
14 public static void main(String argv[]) {
15
16 try {
17
18 File fXmlFile = new File("/Users/mkyong/staff.xml");
19 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
20 DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
21 Document doc = dBuilder.parse(fXmlFile);
22
23 //optional, but recommended
24 //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
25 doc.getDocumentElement().normalize();
26
27 System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
28
29 NodeList nList = doc.getElementsByTagName("staff");
30
31 System.out.println("----------------------------");
32
33 for (int temp = 0; temp < nList.getLength(); temp++) {
34
35 Node nNode = nList.item(temp);
36
37 System.out.println("\nCurrent Element :" + nNode.getNodeName());
38
39 if (nNode.getNodeType() == Node.ELEMENT_NODE) {
40
41 Element eElement = (Element) nNode;
42
43 System.out.println("Staff id : " + eElement.getAttribute("id"));
44 System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
45 System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
46 System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
47 System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
48
49 }
50 }
51 } catch (Exception e) {
52 e.printStackTrace();
53 }
54 }
55
56}
57