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
| package com.datalion.keeweek.parser;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Vector;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import com.datalion.keeweek.util.Chelou;
public class XHTMLParser
{
private Document doc;
private Element root;
private SAXBuilder sxb;
public XHTMLParser(InputStream stream)
{
this.sxb = new SAXBuilder();
try
{
this.sxb.setEntityResolver(new Chelou());
this.doc = this.sxb.build(stream);
}
catch(Exception e)
{
e.printStackTrace();
}
this.root = this.doc.getRootElement();
}
/** Function to seek element by their class name
* @param Name of the class
* @return A vector of element
*/
public Vector<Element> getElementsByClassName(String name)
{
Vector<Element> elts = new Vector<Element>();
Iterator it = this.root.getDescendants();
while(it.hasNext())
{
Object current = it.next();
if(current.getClass().getCanonicalName().equals("org.jdom.Element"))
{
Element elt = (Element) current;
if (elt.getAttribute("class") != null && elt.getAttributeValue("class").equals(name))
{
elts.add(elt);
}
}
}
return elts;
}
/** Retrieve a unique element
* @param The unique identifier of an element
* @return An element
*/
public Element getElementById(String uid)
{
Element wanted = null;
Iterator it = this.root.getDescendants();
while(it.hasNext())
{
Object current = it.next();
if(current.getClass().getCanonicalName().equals("org.jdom.Element"))
{
Element elt = (Element) current;
if (elt.getAttribute("id") != null && elt.getAttributeValue("id").equals(uid))
{
wanted=elt;
}
}
}
return wanted;
}
/** Get all elements which is of type given
* @param The tag (input, textarea, div, p ...)
* @return A vector of element contain each elements
*/
public Vector<Element> getElementsByTagName(String tag)
{
Vector<Element> elts = new Vector<Element>();
Iterator it = this.root.getDescendants();
while(it.hasNext())
{
Object current = it.next();
if(current.getClass().getCanonicalName().equals("org.jdom.Element"))
{
Element elt = (Element) current;
if (elt.getChild(tag)!=null)
{
elts.add(elt);
}
}
}
return elts;
}
/** Search a string in the XHTML page
* @param A string
* @return A vector of element contain each elements
*/
public Vector<Element> search(String pattern)
{
Vector<Element> elts = new Vector<Element>();
Iterator it = this.root.getDescendants();
while(it.hasNext())
{
Object current = it.next();
if(current.getClass().getCanonicalName().equals("org.jdom.Element"))
{
Element elt = (Element) current;
}
}
return elts;
}
} |
Partager