forked from hacker85/JavaLessons
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDomLesson.java
More file actions
69 lines (63 loc) · 2.72 KB
/
Copy pathDomLesson.java
File metadata and controls
69 lines (63 loc) · 2.72 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package xml;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import java.io.File;
import java.io.IOException;
public class DomLesson {
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
//DOM
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("prop.xml"));
Element root = document.getDocumentElement();
System.out.println(root.getTagName());
printElements(root.getChildNodes(), 0);
// NodeList list = root.getChildNodes();
// for (int i = 0; i < list.getHeight(); i++) {
// Node node = list.item(i);
// if(node instanceof Element) {
// System.out.println(node.getNodeName());
// }
// }
}
static void printElements(NodeList list, int tabs) {
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if(node instanceof Element) {
String value = "";
if(!node.getTextContent().trim().isEmpty() && !((Text)node.getFirstChild()).getData().trim().isEmpty() && !((Text)node.getFirstChild()).getData().trim().equals("\n")) {
Text text = (Text)node.getFirstChild();
value += " = " + text.getData().trim();
}
System.out.println(getTab(tabs) + node.getNodeName() + value);
NamedNodeMap attributes = node.getAttributes();
for (int j = 0; j < attributes.getLength(); j++)
{
Node attribute = attributes.item(j);
String name = attribute.getNodeName();
String val = attribute.getNodeValue();
System.out.println("Atributes - " + name + " = " + val);
}
if(node.hasChildNodes()) {
printElements(node.getChildNodes(), ++tabs);
// if(!node.getTextContent().isEmpty()) {
// Text text = (Text)node.getFirstChild();
// System.out.println(text.getData().trim());
// //System.out.println(node.getTextContent());
// }
}
}
}
}
static String getTab(int tabs) {
String str = "";
for (int i = 0; i < tabs; i++) {
str += "\t";
}
return str;
}
}