1 package net.sourceforge.jwebunit; 2 3 import org.w3c.dom.Node ; 4 import org.w3c.dom.NodeList ; 5 import org.w3c.dom.Element ; 6 import org.w3c.dom.CharacterData ; 7 8 import java.util.ArrayList ; 9 10 13 class TextAndElementWalker { 14 private StringBuffer currentText; 15 private ArrayList texts; 16 private ArrayList nodes; 17 private String [] tags; 18 19 public TextAndElementWalker(Element root, String [] tags) { 20 currentText = new StringBuffer (); 21 texts = new ArrayList (); 22 nodes = new ArrayList (); 23 this.tags = tags; 24 walk(root); 25 } 26 27 private void walk(Node node) { 28 if (node instanceof CharacterData ) { 29 currentText.append(((CharacterData ) node).getData()); 30 } else if (node instanceof Element ) { 31 String tag = node.getNodeName(); 32 if (matches(tag)) { 33 rememberElement((Element ) node); 34 } else { 35 NodeList children = node.getChildNodes(); 36 for (int i = 0; i < children.getLength(); i++) { 37 walk(children.item(i)); 38 } 39 } 40 } 41 } 42 43 private boolean matches(String tag) { 44 for (int i = 0; i < tags.length; i++) { 45 if (tag.equalsIgnoreCase(tags[i])) { 46 return true; 47 } 48 } 49 return false; 50 } 51 52 private void rememberElement(Element node) { 53 texts.add(currentText.toString()); 54 nodes.add(node); 55 currentText = new StringBuffer (); 56 } 57 58 public Element getElementAfterText(String label) { 59 int index = indexOfElementAfterText(label); 60 return index == -1 ? null : (Element ) nodes.get(index); 61 } 62 63 private int indexOfElementAfterText(String label) { 64 for (int i = 0; i < nodes.size(); i++) { 65 if (((String ) texts.get(i)).indexOf(label) != -1) { 66 return i; 67 } 68 } 69 return -1; 70 } 71 72 public Element getElementWithTextAfterText(String linkText, String labelText) { 73 int index = indexOfElementAfterText(labelText); 74 if (index != -1) { 75 for (int i = index; i < nodes.size(); i++) { 76 Element node = (Element ) nodes.get(i); 77 if (HttpUnitDialog.nodeContainsText(node, linkText)) { 78 return node; 79 } 80 } 81 } 82 return null; 83 } 84 85 } 86 | Popular Tags |