-
Notifications
You must be signed in to change notification settings - Fork 240
/
DocumentHelper.java
420 lines (364 loc) · 13.9 KB
/
DocumentHelper.java
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/*
* Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
*
* This software is open source.
* See the bottom of this file for the licence.
*/
package org.dom4j;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.dom4j.io.SAXReader;
import org.dom4j.rule.Pattern;
import org.jaxen.VariableContext;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* <code>DocumentHelper</code> is a collection of helper methods for using
* DOM4J.
*
* @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
* @version $Revision: 1.26 $
*/
@SuppressWarnings("unused")
public final class DocumentHelper {
private DocumentHelper() {
}
private static DocumentFactory getDocumentFactory() {
return DocumentFactory.getInstance();
}
// Static helper methods
public static Document createDocument() {
return getDocumentFactory().createDocument();
}
public static Document createDocument(Element rootElement) {
return getDocumentFactory().createDocument(rootElement);
}
public static Element createElement(QName qname) {
return getDocumentFactory().createElement(qname);
}
public static Element createElement(String name) {
return getDocumentFactory().createElement(name);
}
public static Attribute createAttribute(Element owner, QName qname,
String value) {
return getDocumentFactory().createAttribute(owner, qname, value);
}
public static Attribute createAttribute(Element owner, String name,
String value) {
return getDocumentFactory().createAttribute(owner, name, value);
}
public static CDATA createCDATA(String text) {
return DocumentFactory.getInstance().createCDATA(text);
}
public static Comment createComment(String text) {
return DocumentFactory.getInstance().createComment(text);
}
public static Text createText(String text) {
return DocumentFactory.getInstance().createText(text);
}
public static Entity createEntity(String name, String text) {
return DocumentFactory.getInstance().createEntity(name, text);
}
public static Namespace createNamespace(String prefix, String uri) {
return DocumentFactory.getInstance().createNamespace(prefix, uri);
}
public static ProcessingInstruction createProcessingInstruction(String pi,
String d) {
return getDocumentFactory().createProcessingInstruction(pi, d);
}
public static ProcessingInstruction createProcessingInstruction(String pi,
Map<String, String> data) {
return getDocumentFactory().createProcessingInstruction(pi, data);
}
public static QName createQName(String localName, Namespace namespace) {
return getDocumentFactory().createQName(localName, namespace);
}
public static QName createQName(String localName) {
return getDocumentFactory().createQName(localName);
}
/**
* <p>
* <code>createXPath</code> parses an XPath expression and creates a new
* XPath <code>XPath</code> instance using the singleton {@link
* DocumentFactory}.
* </p>
*
* @param xpathExpression
* is the XPath expression to create
*
* @return a new <code>XPath</code> instance
*
* @throws InvalidXPathException
* if the XPath expression is invalid
*/
public static XPath createXPath(String xpathExpression)
throws InvalidXPathException {
return getDocumentFactory().createXPath(xpathExpression);
}
/**
* <p>
* <code>createXPath</code> parses an XPath expression and creates a new
* XPath <code>XPath</code> instance using the singleton {@link
* DocumentFactory}.
* </p>
*
* @param xpathExpression
* is the XPath expression to create
* @param context
* is the variable context to use when evaluating the XPath
*
* @return a new <code>XPath</code> instance
*
* @throws InvalidXPathException
* if the XPath expression is invalid
*/
public static XPath createXPath(String xpathExpression,
VariableContext context) throws InvalidXPathException {
return getDocumentFactory().createXPath(xpathExpression, context);
}
/**
* <p>
* <code>createXPathFilter</code> parses a NodeFilter from the given XPath
* filter expression using the singleton {@link DocumentFactory}. XPath
* filter expressions occur within XPath expressions such as
* <code>self::node()[ filterExpression ]</code>
* </p>
*
* @param xpathFilterExpression
* is the XPath filter expression to create
*
* @return a new <code>NodeFilter</code> instance
*/
public static NodeFilter createXPathFilter(String xpathFilterExpression) {
return getDocumentFactory().createXPathFilter(xpathFilterExpression);
}
/**
* <p>
* <code>createPattern</code> parses the given XPath expression to create
* an XSLT style {@link Pattern}instance which can then be used in an XSLT
* processing model.
* </p>
*
* @param xpathPattern
* is the XPath pattern expression to create
*
* @return a new <code>Pattern</code> instance
*/
public static Pattern createPattern(String xpathPattern) {
return getDocumentFactory().createPattern(xpathPattern);
}
/**
* <p>
* <code>selectNodes</code> performs the given XPath expression on the
* {@link List}of {@link Node}instances appending all the results together
* into a single list.
* </p>
*
* @param xpathFilterExpression
* is the XPath filter expression to evaluate
* @param nodes
* is the list of nodes on which to evalute the XPath
*
* @return the results of all the XPath evaluations as a single list
*/
public static List<Node> selectNodes(String xpathFilterExpression, List<Node> nodes) {
XPath xpath = createXPath(xpathFilterExpression);
return xpath.selectNodes(nodes);
}
/**
* <p>
* <code>selectNodes</code> performs the given XPath expression on the
* {@link List}of {@link Node}instances appending all the results together
* into a single list.
* </p>
*
* @param xpathFilterExpression
* is the XPath filter expression to evaluate
* @param node
* is the Node on which to evalute the XPath
*
* @return the results of all the XPath evaluations as a single list
*/
public static List<Node> selectNodes(String xpathFilterExpression, Node node) {
XPath xpath = createXPath(xpathFilterExpression);
return xpath.selectNodes(node);
}
/**
* <p>
* <code>sort</code> sorts the given List of Nodes using an XPath
* expression as a {@link java.util.Comparator}.
* </p>
*
* @param list
* is the list of Nodes to sort
* @param xpathExpression
* is the XPath expression used for comparison
*/
public static void sort(List<Node> list, String xpathExpression) {
XPath xpath = createXPath(xpathExpression);
xpath.sort(list);
}
/**
* <p>
* <code>sort</code> sorts the given List of Nodes using an XPath
* expression as a {@link java.util.Comparator}and optionally removing
* duplicates.
* </p>
*
* @param list
* is the list of Nodes to sort
* @param expression
* is the XPath expression used for comparison
* @param distinct
* if true then duplicate values (using the sortXPath for
* comparisions) will be removed from the List
*/
public static void sort(List<Node> list, String expression, boolean distinct) {
XPath xpath = createXPath(expression);
xpath.sort(list, distinct);
}
/**
* <p>
* <code>parseText</code> parses the given text as an XML document and
* returns the newly created Document.
* </p>
*
* Loading external DTD and entities is disabled (if it is possible) for security reasons.
*
* @param text
* the XML text to be parsed
*
* @return a newly parsed Document
*
* @throws DocumentException
* if the document could not be parsed
*/
public static Document parseText(String text) throws DocumentException {
SAXReader reader = new SAXReader();
try {
reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
} catch (SAXException e) {
//Parse with external resources downloading allowed.
}
String encoding = getEncoding(text);
InputSource source = new InputSource(new StringReader(text));
source.setEncoding(encoding);
Document result = reader.read(source);
// if the XML parser doesn't provide a way to retrieve the encoding,
// specify it manually
if (result.getXMLEncoding() == null) {
result.setXMLEncoding(encoding);
}
return result;
}
private static String getEncoding(String text) {
String result = null;
String xml = text.trim();
if (xml.startsWith("<?xml")) {
int end = xml.indexOf("?>");
String sub = xml.substring(0, end);
StringTokenizer tokens = new StringTokenizer(sub, " =\"\'");
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken();
if ("encoding".equals(token)) {
if (tokens.hasMoreTokens()) {
result = tokens.nextToken();
}
break;
}
}
}
return result;
}
/**
* <p>
* makeElement
* </p>
* a helper method which navigates from the given Document or Element node
* to some Element using the path expression, creating any necessary
* elements along the way. For example the path <code>a/b/c</code> would
* get the first child <a> element, which would be created if it did
* not exist, then the next child <b> and so on until finally a
* <c> element is returned.
*
* @param source
* is the Element or Document to start navigating from
* @param path
* is a simple path expression, seperated by '/' which denotes
* the path from the source to the resulting element such as
* a/b/c
*
* @return the first Element on the given path which either already existed
* on the path or were created by this method.
*/
public static Element makeElement(Branch source, String path) {
StringTokenizer tokens = new StringTokenizer(path, "/");
Element parent;
if (source instanceof Document) {
Document document = (Document) source;
parent = document.getRootElement();
// lets throw a NoSuchElementException
// if we are given an empty path
String name = tokens.nextToken();
if (parent == null) {
parent = document.addElement(name);
}
} else {
parent = (Element) source;
}
Element element = null;
while (tokens.hasMoreTokens()) {
String name = tokens.nextToken();
if (name.indexOf(':') > 0) {
element = parent.element(parent.getQName(name));
} else {
element = parent.element(name);
}
if (element == null) {
element = parent.addElement(name);
}
parent = element;
}
return element;
}
}
/*
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain copyright statements and
* notices. Redistributions must also contain a copy of this document.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name "DOM4J" must not be used to endorse or promote products derived
* from this Software without prior written permission of MetaStuff, Ltd. For
* written permission, please contact dom4j-info@metastuff.com.
*
* 4. Products derived from this Software may not be called "DOM4J" nor may
* "DOM4J" appear in their names without prior written permission of MetaStuff,
* Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
*
* 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
*
* THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
*/