source: trunk/gli/src/org/greenstone/gatherer/util/XMLTools.java@ 9037

Last change on this file since 9037 was 9037, checked in by mdewsnip, 19 years ago

Now preserves whitespace in XML files.

  • Property svn:keywords set to Author Date Id Revision
File size: 6.5 KB
Line 
1package org.greenstone.gatherer.util;
2
3
4import java.io.*;
5import java.net.*;
6import java.util.*;
7import org.apache.xerces.parsers.*;
8import org.apache.xml.serialize.*;
9import org.greenstone.gatherer.DebugStream;
10import org.w3c.dom.*;
11import org.xml.sax.*;
12
13
14/** This class is a static class containing useful XML functions */
15public class XMLTools
16{
17 /** Remove all of the child nodes from a certain node. */
18 static final public void clear(Node node)
19 {
20 while (node.hasChildNodes()) {
21 node.removeChild(node.getFirstChild());
22 }
23 }
24
25
26 static public ArrayList getChildElementsByTagName(Element parent_element, String element_name)
27 {
28 ArrayList child_elements = new ArrayList();
29
30 NodeList children_nodelist = parent_element.getChildNodes();
31 for (int i = 0; i < children_nodelist.getLength(); i++) {
32 Node child_node = children_nodelist.item(i);
33 if (child_node.getNodeType() == Node.ELEMENT_NODE && child_node.getNodeName().equals(element_name)) {
34 child_elements.add(child_node);
35 }
36 }
37
38 return child_elements;
39 }
40
41
42 static public String getElementTextValue(Element element)
43 {
44 // Find the first text node child
45 NodeList children_nodelist = element.getChildNodes();
46 for (int i = 0; i < children_nodelist.getLength(); i++) {
47 Node child_node = children_nodelist.item(i);
48 if (child_node.getNodeType() == Node.TEXT_NODE) {
49 return child_node.getNodeValue();
50 }
51 }
52
53 // None found
54 return "";
55 }
56
57
58 /** Method to retrieve the value of a given node.
59 * @param element The <strong>Element</strong> whose value we wish to find.
60 * Soon to be deprecated!
61 */
62 static final public String getValue(Node element) {
63 // If we've been given a subject node first retrieve its value node.
64 if(element.getNodeName().equals("Subject")) {
65 element = getNodeFromNamed(element, "Value");
66 }
67 // If we've got a value node, then reconstruct the text. Remember that DOM will split text over 256 characters into several text nodes
68 if(element != null && element.hasChildNodes()) {
69 StringBuffer text_buffer = new StringBuffer();
70 NodeList text_nodes = element.getChildNodes();
71 for(int i = 0; i < text_nodes.getLength(); i++) {
72 Node possible_text = text_nodes.item(i);
73 if(possible_text.getNodeName().equals(StaticStrings.TEXT_NODE)) {
74 text_buffer.append(possible_text.getNodeValue());
75 }
76 }
77 return text_buffer.toString();
78 }
79 return "";
80 }
81
82
83 /** Method to retrieve from the node given, a certain child node with the specified name.
84 * @param parent The <strong>Node</strong> whose children should be searched.
85 * @param name The required nodes name as a <strong>String</strong>.
86 * @return The requested <strong>Node</strong> if it is found, <i>null</i> otherwise.
87 * Soon to be deprecated!
88 */
89 static final public Node getNodeFromNamed(Node parent, String name) {
90 Node child = null;
91 for(Node i = parent.getFirstChild(); i != null && child == null;
92 i = i.getNextSibling()) {
93 if(i.getNodeName().equals(name)) {
94 child = i;
95 }
96 }
97 return child;
98 }
99
100
101 /** Parse an XML document from a given file */
102 static public Document parseXMLFile(File xml_file)
103 {
104 try {
105 return parseXML(new FileInputStream(xml_file));
106 }
107 catch (Exception exception) {
108 DebugStream.printStackTrace(exception);
109 return null;
110 }
111 }
112
113
114 /** Parse an XML document from a given input stream */
115 static public Document parseXML(InputStream xml_input_stream)
116 {
117 Document document = null;
118
119 try {
120 InputStreamReader isr = new InputStreamReader(xml_input_stream, "UTF-8");
121 Reader r = new BufferedReader(isr);
122 InputSource isc = new InputSource(r);
123 DOMParser parser = new DOMParser();
124 parser.setFeature("http://xml.org/sax/features/validation", false);
125 parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
126 // May or may not be ignored, the documentation for Xerces is contradictory. If it works then parsing -should- be faster.
127 parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", true);
128 parser.setFeature("http://apache.org/xml/features/dom/include-ignorable-whitespace", false);
129 parser.parse(isc);
130 document = parser.getDocument();
131 isr.close();
132 xml_input_stream.close();
133 }
134 catch (Exception exception) {
135 DebugStream.printStackTrace(exception);
136 }
137
138 return document;
139 }
140
141
142 /** Removes characters that are invalid in XML (see http://www.w3.org/TR/2000/REC-xml-20001006#charsets) */
143 static public String removeInvalidCharacters(String text)
144 {
145 char[] safe_characters = new char[text.length()];
146 int j = 0;
147
148 char[] raw_characters = new char[text.length()];
149 text.getChars(0, text.length(), raw_characters, 0);
150 for (int i = 0; i < raw_characters.length; i++) {
151 char character = raw_characters[i];
152 if ((character >= 0x20 && character <= 0xD7FF) || character == 0x09 || character == 0x0A || character == 0x0D || (character >= 0xE000 && character <= 0xFFFD) || (character >= 0x10000 && character <= 0x10FFFF)) {
153 safe_characters[j] = character;
154 j++;
155 }
156 }
157
158 return new String(safe_characters, 0, j);
159 }
160
161
162 /** Set the #text node value of some element.
163 * @param element the Element whose value we wish to set
164 * @param value the new value for the element as a String
165 * Soon to be deprecated!
166 */
167 static final public void setValue(Element element, String value) {
168 // Remove any existing child node(s)
169 clear(element);
170 // Add new text node.
171 if (value != null) {
172 element.appendChild(element.getOwnerDocument().createTextNode(value));
173 }
174 }
175
176
177 /** Write an XML document to a given file */
178 static public void writeXMLFile(File xml_file, Document document)
179 {
180 try {
181 OutputStream os = new FileOutputStream(xml_file);
182 // Create an output format for our document.
183 OutputFormat f = new OutputFormat(document);
184 f.setEncoding("UTF-8");
185 f.setIndenting(true);
186 f.setLineWidth(0); // Why isn't this working!
187 f.setPreserveSpace(true);
188 // Create the necessary writer stream for serialization.
189 OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
190 Writer w = new BufferedWriter(osw);
191 // Generate a new serializer from the above.
192 XMLSerializer s = new XMLSerializer(w, f);
193 s.asDOMSerializer();
194 // Finally serialize the document to file.
195 s.serialize(document);
196 // And close.
197 os.close();
198 }
199 catch (Exception exception) {
200 DebugStream.printStackTrace(exception);
201 }
202 }
203}
Note: See TracBrowser for help on using the repository browser.