forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaXmlDomReadElements.java
More file actions
39 lines (29 loc) · 1.25 KB
/
JavaXmlDomReadElements.java
File metadata and controls
39 lines (29 loc) · 1.25 KB
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
package com.zetcode;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.NodeIterator;
import org.xml.sax.SAXException;
public class JavaXmlDomReadElements {
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder loader = factory.newDocumentBuilder();
Document document = loader.parse("src/main/resources/continents.xml");
DocumentTraversal trav = (DocumentTraversal) document;
NodeIterator it = trav.createNodeIterator(document.getDocumentElement(),
NodeFilter.SHOW_ELEMENT, null, true);
int c = 1;
for (Node node = it.nextNode(); node != null;
node = it.nextNode()) {
String name = node.getNodeName();
System.out.printf("%d %s%n", c, name);
c++;
}
}
}