Skip to content

Instantly share code, notes, and snippets.

@ox
Created April 5, 2012 02:09
Show Gist options
  • Save ox/2307436 to your computer and use it in GitHub Desktop.
Save ox/2307436 to your computer and use it in GitHub Desktop.
AddTag for DOM Tree
public void addTag(String word, String tag) {
recursiveAddTag(root, word, tag);
}
private void recursiveAddTag(TagNode parent, String word, String tag) {
for (TagNode ptr=parent; ptr != null;ptr=ptr.sibling) {
String[] parts = ptr.tag.split(word+"[^\\s\\w]*",2);
if(parts.length > 1) {
System.out.println("operating on: " + java.util.Arrays.toString(parts));
if(ptr.tag.equals(word)) {
ptr.tag = tag;
ptr.firstChild = new TagNode(word, null, null);
return;
} else if(parts[0].equals("")) {
ptr.tag = tag;
ptr.firstChild = new TagNode(word, null, null);
ptr.sibling = new TagNode(parts[1], null, ptr.sibling);
} else if(parts[1].equals("")) {
ptr.tag = parts[0];
ptr.sibling = new TagNode(tag, new TagNode(word, null, null), ptr.sibling);
} else {
ptr.tag = parts[0];
TagNode next = new TagNode(parts[1], null, ptr.sibling);
ptr.sibling = new TagNode(tag, new TagNode(word, null, null), next);
}
return;
} else if(ptr.firstChild != null) recursiveAddTag(ptr.firstChild, word, tag);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment