1 package org.opentrafficsim.editor;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.net.URI;
6 import java.util.ArrayList;
7
8 import javax.xml.parsers.DocumentBuilder;
9 import javax.xml.parsers.DocumentBuilderFactory;
10 import javax.xml.parsers.ParserConfigurationException;
11
12 import org.w3c.dom.Document;
13 import org.w3c.dom.Node;
14 import org.xml.sax.SAXException;
15
16
17
18
19
20
21
22
23
24 public final class DocumentReader
25 {
26
27
28
29
30 private DocumentReader()
31 {
32
33 }
34
35
36
37
38
39
40
41
42
43 public static Document open(final URI file) throws SAXException, IOException, ParserConfigurationException
44 {
45 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
46
47 dbf.setIgnoringComments(true);
48 dbf.setIgnoringElementContentWhitespace(true);
49 DocumentBuilder db = dbf.newDocumentBuilder();
50 Document doc = db.parse(new File(file));
51 return doc;
52 }
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71 public static String getAnnotation(final Node node, final String element, final String source)
72 {
73 for (Node child : DocumentReader.getChildren(node, "xsd:annotation"))
74 {
75 for (Node annotation : DocumentReader.getChildren(child, element))
76 {
77 String appInfoSource = DocumentReader.getAttribute(annotation, "source");
78 if (appInfoSource != null && appInfoSource.equals(source))
79 {
80 StringBuilder str = new StringBuilder();
81 for (int appIndex = 0; appIndex < annotation.getChildNodes().getLength(); appIndex++)
82 {
83 Node appInfo = annotation.getChildNodes().item(appIndex);
84 if (appInfo.getNodeName().equals("#text"))
85 {
86 str.append(appInfo.getNodeValue());
87 }
88 }
89
90 return str.toString().replaceAll("\\s", " ").replaceAll("\\s{2,}", " ").trim();
91 }
92 }
93 }
94 return null;
95 }
96
97
98
99
100
101
102
103
104
105
106
107
108
109 public static String getAttribute(final Node node, final String name)
110 {
111 return node.hasAttributes() && node.getAttributes().getNamedItem(name) != null
112 ? node.getAttributes().getNamedItem(name).getNodeValue() : null;
113 }
114
115
116
117
118
119
120
121 public static Node getChild(final Node node, final String type)
122 {
123 if (node.hasChildNodes())
124 {
125 for (int childIndex = 0; childIndex < node.getChildNodes().getLength(); childIndex++)
126 {
127 Node child = node.getChildNodes().item(childIndex);
128 if (child.getNodeName().equals(type))
129 {
130 return child;
131 }
132 }
133 }
134 return null;
135 }
136
137
138
139
140
141
142
143 public static ArrayList<Node> getChildren(final Node node, final String type)
144 {
145 ArrayList<Node> children = new ArrayList<>();
146 if (node.hasChildNodes())
147 {
148 for (int childIndex = 0; childIndex < node.getChildNodes().getLength(); childIndex++)
149 {
150 Node child = node.getChildNodes().item(childIndex);
151 if (child.getNodeName().equals(type))
152 {
153 children.add(child);
154 }
155 }
156 }
157 return children;
158 }
159
160 }