KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > gulden > util > xml > XMLToolbox


1 /*
2  * Project: Gulden Utilies
3  * Class: de.gulden.util.xml.XMLToolbox
4  * Version: snapshot-beautyj-1.1
5  *
6  * Date: 2004-09-29
7  *
8  * This is a snapshot version of the Gulden Utilities,
9  * it is not released as a seperate version.
10  *
11  * Note: Contains auto-generated Javadoc comments created by BeautyJ.
12  *
13  * This is licensed under the GNU Lesser General Public License (LGPL)
14  * and comes with NO WARRANTY.
15  *
16  * Author: Jens Gulden
17  * Email: amoda@jensgulden.de
18  */

19
20 package de.gulden.util.xml;
21
22 import de.gulden.util.Toolbox;
23 import de.gulden.util.xml.NodeListImpl;
24 import java.io.*;
25 import java.util.*;
26 import java.util.Collection JavaDoc;
27 import javax.xml.parsers.*;
28 import org.w3c.dom.*;
29
30 /**
31  * Class XMLToolbox.
32  *
33  * @author Jens Gulden
34  * @version snapshot-beautyj-1.1
35  */

36 public class XMLToolbox {
37
38     // ------------------------------------------------------------------------
39
// --- static field ---
40
// ------------------------------------------------------------------------
41

42     /**
43      * The parse x m l document builder.
44      */

45     protected static DocumentBuilder parseXMLDocumentBuilder;
46
47
48     // ------------------------------------------------------------------------
49
// --- static methods ---
50
// ------------------------------------------------------------------------
51

52     /**
53      * Creates the default document builder.
54      */

55     public static DocumentBuilder createDefaultDocumentBuilder() {
56         try {
57             javax.xml.parsers.DocumentBuilderFactory JavaDoc factory=javax.xml.parsers.DocumentBuilderFactory.newInstance();
58             return factory.newDocumentBuilder();
59         } catch (Exception JavaDoc e) {
60             System.err.println("fatal error: cannot create default DocumentBuilder");
61             System.err.println(e.getClass().getName()+" - "+e.getMessage());
62             e.printStackTrace(System.err);
63             System.exit(2);
64             return null;
65         }
66     }
67
68     /**
69      * Creates the default document builder.
70      */

71     public static DocumentBuilder createDefaultDocumentBuilder(boolean validating, boolean namespaceAware, boolean ignoringElementContentWhitespace, boolean ignoringComments, boolean expandEntityReferences, boolean coalescing) {
72         try {
73             javax.xml.parsers.DocumentBuilderFactory JavaDoc factory=javax.xml.parsers.DocumentBuilderFactory.newInstance();
74             factory.setValidating(validating);
75             factory.setNamespaceAware(namespaceAware);
76             factory.setIgnoringElementContentWhitespace(ignoringElementContentWhitespace);
77             factory.setIgnoringComments(ignoringComments);
78             factory.setExpandEntityReferences(expandEntityReferences);
79             factory.setCoalescing(coalescing);
80             return factory.newDocumentBuilder();
81         } catch (Exception JavaDoc e) {
82             System.err.println("fatal error: cannot create default DocumentBuilder");
83             System.err.println(e.getClass().getName()+" - "+e.getMessage());
84             e.printStackTrace(System.err);
85             System.exit(2);
86             return null;
87         }
88     }
89
90     /**
91      * Returns the first child with the specified tagname.
92      */

93     public static Element getChild(Element e, String JavaDoc tagname) {
94         Node n=e.getFirstChild();
95         while (n!=null)
96         {
97           if (n instanceof Element)
98           {
99             Element c=(Element)n;
100             if (c.getTagName().equals(tagname))
101             {
102               return c;
103             }
104           }
105           n=n.getNextSibling();
106         }
107         return null;
108     }
109
110     /**
111      * Returns the first child with the specified tagname and the named attribute set to the given value.
112      */

113     public static Element getChild(Element e, String JavaDoc tagname, String JavaDoc attributeName, String JavaDoc attributeValue) {
114         Node n=e.getFirstChild();
115         while (n!=null) {
116             if (n instanceof Element) {
117                 Element c=(Element)n;
118                 if (c.getTagName().equals(tagname)) {
119                     if (c.hasAttribute(attributeName) && c.getAttribute(attributeName).equals(attributeValue)) {
120                         return c;
121                     }
122                 }
123             }
124             n=n.getNextSibling();
125         }
126         return null;
127     }
128
129     /**
130      * Returns the child required.
131      */

132     public static Element getChildRequired(Element e, String JavaDoc tagname) throws XMLException {
133         Element c=getChild(e,tagname);
134         if (c==null)
135         {
136           throw new XMLException("child tag '<"+tagname+"'> required",e);
137         }
138         return c;
139     }
140
141     /**
142      * Returns the attribute required.
143      */

144     public static String JavaDoc getAttributeRequired(Element e, String JavaDoc att) throws XMLException {
145         String JavaDoc a=e.getAttribute(att);
146         if ((a==null)||(a.length()==0))
147         {
148           throw new XMLException("attribute '"+att+"' required",e);
149         }
150         return a;
151     }
152
153     /**
154      * Returns the children.
155      */

156     public static NodeListCollection getChildren(Element e, String JavaDoc tagname) {
157         NodeListImpl nl=new NodeListImpl();
158         Node n=e.getFirstChild();
159         while (n!=null)
160         {
161           if (n instanceof Element)
162           {
163             Element c=(Element)n;
164             if (c.getTagName().equals(tagname))
165             {
166               nl.add(c);
167             }
168           }
169           n=n.getNextSibling();
170         }
171         return nl;
172     }
173
174     public static boolean isYesAttribute(Element e, String JavaDoc attr) {
175         return getBooleanAttribute(e,attr,false);
176     }
177
178     /**
179      * Returns the text.
180      */

181     public static String JavaDoc getText(Element e) {
182         Node n=e.getFirstChild();
183         if ((n!=null)&&(n instanceof CharacterData))
184         {
185           String JavaDoc t=((CharacterData)n).getData();
186           return t;
187         }
188         else
189         {
190           return null;
191         }
192     }
193
194     /**
195      * Returns the child text.
196      */

197     public static String JavaDoc getChildText(Element e, String JavaDoc tagname) {
198         Element child=getChild(e,tagname);
199         if (child!=null)
200         {
201           return getText(child);
202         }
203         else
204         {
205           return null;
206         }
207     }
208
209     public static void requireTagName(Element element, String JavaDoc name) throws XMLException {
210         if (!element.getTagName().equals(name)) {
211             throw new XMLException("illegal XML tag - expected <"+name+">",element);
212         }
213     }
214
215     /**
216      * Returns the first child.
217      */

218     public static Element getFirstChild(Element e) {
219         return getSelfOrFollowingElement(e.getFirstChild());
220     }
221
222     /**
223      * Returns the children.
224      */

225     public static NodeListCollection getChildren(Element e) {
226         NodeListCollection c=new NodeListImpl();
227         Element ee=getFirstChild(e);
228         while (ee!=null) {
229             c.add(ee);
230             ee=getFollowingElement(ee);
231         }
232         return c;
233     }
234
235     /**
236      * Returns the self or following element.
237      */

238     public static Element getSelfOrFollowingElement(Node n) {
239         while ((n!=null)&&(!(n instanceof Element))) {
240             n=n.getNextSibling();
241         }
242         return (Element)n;
243     }
244
245     /**
246      * Returns the following element.
247      */

248     public static Element getFollowingElement(Node n) {
249         // DEPRECATED
250
return getNextSibling(n);
251     }
252
253     /**
254      * Returns the langstring.
255      */

256     public static String JavaDoc getLangstring(Element element, String JavaDoc countryCode) {
257         if (element!=null) { // make null-safe to allow easier calling from nested functions
258
org.w3c.dom.NodeList JavaDoc nl=getChildren(element,"langstring");
259             if (nl.getLength()>0) {
260                 org.w3c.dom.Element JavaDoc defaultElement=null;
261                 for (int i=0;i<nl.getLength();i++) {
262                     Element e=(Element)nl.item(i);
263                     String JavaDoc c=e.getAttribute("lang");
264                     if ((c.equals(""))&&(defaultElement==null)) {
265                         defaultElement=e;
266                         if (countryCode==null) {
267                             return getText(e); // default found
268
}
269                     } else if ((countryCode!=null)&&(countryCode.equalsIgnoreCase(c))) { // explicit lang wanted
270
return getText(e); // language found
271
}
272                 }
273                 // not explicitly found, use default
274
if (defaultElement!=null) {
275                     // (countryCode!=null) here, otherwise already returned
276
return getText(defaultElement); // return default if there was a <langstring> without explicit lang attribute, although AN EXPLICIT LANGUAGE HAD BEEN REQUESTED HERE
277
} else {
278                     // last chance: if no default <langstring> without lang attribute
279
if (countryCode==null) { // but also no lang was explicitly requested
280
return getText((Element)nl.item(0)); // use first entry as default
281
} else {
282                         return null; // not found
283
}
284                 }
285             } else {
286                 return null;
287             }
288         } else {
289             return null;
290         }
291     }
292
293     /**
294      * Returns the langstring.
295      */

296     public static String JavaDoc getLangstring(Element element) {
297         return getLangstring(element,null); // default language
298
}
299
300     public static String JavaDoc translateJavaNameToXMLName(String JavaDoc name) {
301         int pos=0;
302         // skip while uppercase letters
303
while ((pos<name.length())&&(Character.isUpperCase(name.charAt(pos)))) {
304             pos++;
305         }
306         // skip to first uppercase letter
307
while ((pos<name.length())&&(Character.isLowerCase(name.charAt(pos)))) {
308             pos++;
309         }
310         // build result
311
if (pos>0) {
312             if (pos<name.length()) {
313                 return name.substring(0,pos).toLowerCase()+"-"+translateJavaNameToXMLName(name.substring(pos));
314             } else {
315                 return name.toLowerCase();
316             }
317         } else {
318             return "";
319         }
320     }
321
322     public static String JavaDoc translateXMLNameToJavaName(String JavaDoc name) {
323         // name must not be ""
324
StringTokenizer st=new StringTokenizer(name,"-",false);
325         StringBuffer JavaDoc sb=new StringBuffer JavaDoc(st.nextToken());
326         while (st.hasMoreTokens()) {
327             String JavaDoc t=st.nextToken();
328             sb.append(de.gulden.util.Toolbox.capitalize(t));
329         }
330         return sb.toString();
331     }
332
333     /**
334      * Returns the next sibling.
335      */

336     public static Element getNextSibling(Node n) {
337         return getSelfOrFollowingElement(n.getNextSibling());
338     }
339
340     /**
341      * Returns the children.
342      */

343     public static NodeListCollection getChildren(Element e, String JavaDoc[] tagnames) {
344         NodeListImpl nl=new NodeListImpl();
345         Node n=e.getFirstChild();
346         while (n!=null) {
347           if (n instanceof Element) {
348             Element c=(Element)n;
349             if (Toolbox.arrayContains(tagnames,c.getTagName())) {
350               nl.add(c);
351             }
352           }
353           n=n.getNextSibling();
354         }
355         return nl;
356     }
357
358     /**
359      * Parses the x m l.
360      */

361     public static Element parseXML(String JavaDoc s) throws XMLException {
362         try {
363             if (parseXMLDocumentBuilder==null) {
364                 parseXMLDocumentBuilder=createDefaultDocumentBuilder();
365                 if (parseXMLDocumentBuilder==null) {
366                     throw new XMLException("Internal error: cannot parse XML - could not create document builder");
367                 }
368             }
369             java.io.StringBufferInputStream JavaDoc in=new java.io.StringBufferInputStream JavaDoc(s);
370             org.w3c.dom.Document JavaDoc doc=parseXMLDocumentBuilder.parse(in);
371             Element xml=doc.getDocumentElement();
372             return xml;
373         } catch (java.io.IOException JavaDoc ioe) {
374             throw new XMLException("cannot parse XML",ioe);
375         } catch (org.xml.sax.SAXException JavaDoc saxe) {
376             throw new XMLException("cannot parse XML",saxe);
377         }
378     }
379
380     public static String JavaDoc formatXML(Node xml, boolean indenting, boolean preserveSpace) {
381         // returns null in case of errors
382
// trows Error if xml is not of type Document or Element
383
try {
384             java.io.StringWriter JavaDoc out=new java.io.StringWriter JavaDoc();
385             org.apache.xml.serialize.OutputFormat outputFormat=new org.apache.xml.serialize.OutputFormat();
386             outputFormat.setIndenting(indenting);
387             outputFormat.setPreserveSpace(preserveSpace);
388             org.apache.xml.serialize.XMLSerializer serializer=new org.apache.xml.serialize.XMLSerializer(out,outputFormat);
389             org.apache.xml.serialize.DOMSerializer domSerializer=serializer.asDOMSerializer();
390             if (xml instanceof Element) {
391                 domSerializer.serialize((Element)xml);
392             } else if (xml instanceof Document) {
393                 domSerializer.serialize((Document)xml);
394             } else {
395                 throw new Error JavaDoc("internal error: can only xml-serialize objects of type Element or Document");
396             }
397             return out.toString();
398         } catch (java.io.IOException JavaDoc ioe) {
399             return null;
400         }
401     }
402
403     /**
404      * Returns the boolean attribute.
405      */

406     public static boolean getBooleanAttribute(Element e, String JavaDoc attr, boolean deflt) {
407         String JavaDoc a=e.getAttribute(attr);
408         if (Toolbox.empty(a)) {
409             return deflt;
410         } else {
411             a=a.trim().toLowerCase();
412             if (deflt==true) {
413                 return !Toolbox.isNo(a);
414             } else {
415                 return Toolbox.isYes(a);
416             }
417         }
418     }
419
420     /**
421      * <p>
422      * Returns an attribute's value.
423      * </p>
424      * <p>
425      */

426     public static String JavaDoc getAttribute(Element e, String JavaDoc name, String JavaDoc deflt) {
427         boolean has=e.hasAttribute(name);
428         if (has) {
429             return e.getAttribute(name);
430         } else {
431             return deflt;
432         }
433     }
434
435     /**
436      * <p>
437      * Returns an attribute's value. Note that unlike
438      * org.w3c.dom.Element.getAttribute(name), this method returns <b>null</b>
439      * if the attribute does not exist on the element. The empty string is only
440      * returned if the attribute actually contains the empty string as value.
441      * </p>
442      * <p>
443      *
444      * @param e The element which carries an attribute.
445      * </p>
446      * <p>
447      * @param name The name of the attribute.
448      * </p>
449      * <p>
450      * @return a String with the attribtue's value, <b>null</b> if the
451      * attribute is absent on the element.
452      * </p>
453      */

454     public static String JavaDoc getAttribute(Element e, String JavaDoc name) {
455         return getAttribute(e,name,null);
456     }
457
458     public static String JavaDoc xmlEscape(String JavaDoc s) {
459         // needed optimization:
460
StringBuffer JavaDoc sb=new StringBuffer JavaDoc();
461         int len=s.length();
462         int lastPos=0;
463         int nextOpen=s.indexOf('<');
464         int nextClose=s.indexOf('>');
465         boolean opens=(nextOpen!=-1);
466         boolean closes=(nextClose!=-1);
467         do {
468         if ( (opens && !closes) || ( opens /* && closes */ && (nextOpen<nextClose)) ) {
469         String JavaDoc part=s.substring(lastPos,nextOpen);
470         sb.append(part);
471         sb.append("&#60;");
472         lastPos=nextOpen+1;
473         nextOpen=s.indexOf('<',lastPos);
474         opens=(nextOpen!=-1);
475         } else if (closes) { // ( closes && ! opens ) || ( closes /* && opens */ && (nextClose<nextOpen) )
476
String JavaDoc part=s.substring(lastPos,nextClose);
477         sb.append(part);
478         sb.append("&#62;");
479         lastPos=nextClose+1;
480         nextClose=s.indexOf('>',lastPos);
481         closes=(nextClose!=-1);
482         }
483         } while (opens||closes);
484         if (lastPos<len) {
485         String JavaDoc rest=s.substring(lastPos);
486         sb.append(rest);
487         }
488         return sb.toString();
489     }
490
491     public static String JavaDoc xmlEscapeAll(String JavaDoc s) {
492         char[] c={ '<', '>', '\"', '\'', '\n', '\r' };
493         String JavaDoc[] r={ "&#60;", "&#62;", "&#34;", "&#39;", "&#010;", "" };
494         return Toolbox.replaceCharsWithStrings(s,c,r);
495     }
496
497 } // end XMLToolbox
498
Popular Tags