The list of methods to do XML Node Previous are organized into topic(s).
int
countElementsBefore(Node node, String tagName) Count the DOM element nodes before the supplied node, having the specified tag name, not including the node itself.
Node parent = node.getParentNode();
if (parent == null) {
System.out.println("Cannot count nodes before [" + node + "]. [" + node + "] has no parent.");
return 0;
NodeList siblings = parent.getChildNodes();
int count = 0;
int siblingCount = siblings.getLength();
...
int
countElementsBefore(Node node, String tagName) Count the DOM element nodes before the supplied node, having the specified tag name, not including the node itself.
Node parent = node.getParentNode();
NodeList siblings = parent.getChildNodes();
int count = 0;
int siblingCount = siblings.getLength();
for (int i = 0; i < siblingCount; i++) {
Node sibling = siblings.item(i);
if (sibling == node) {
break;
...
List
getAncesters(Node node) Get a list of ancester nodes starting from the Document till the node.
List list = new ArrayList();
while (node != null) {
list.add(node);
if (node instanceof Document) {
break;
node = node.getParentNode();
if (node == null) {
return null;
Collections.reverse(list);
list.add(null);
return list;
Node
getAncestor(Node node, String ancestorName) If
node has an ancestor with name
ancestorName, return that ancestor.
Node p = node;
while ((p = p.getParentNode()) != null) {
if (p.getNodeName().equals(ancestorName))
return p;
return null;
Node
getAncestorNode(Node visualNode, String tagName) get Ancestor Node
if (tagName == null)
return null;
Node element = visualNode;
while (true) {
if (tagName.equalsIgnoreCase(element.getNodeName())) {
return element;
element = element.getParentNode();
...
List
getAncestors(Node node)
get Ancestors
final List<Node> ancestors = new ArrayList<Node>();
while (node != null) {
ancestors.add(node);
node = node.getParentNode();
return ancestors;
Node
getPrevious(Node node) Get the previous node in a DFS preorder traversal
Node previous;
if (node == null)
return null;
if ((previous = node.getPreviousSibling()) != null) {
for (; previous.getLastChild() != null; previous = previous.getLastChild()) {
return previous;
return node.getParentNode();
String
getPreviousComment(Node element) get Previous Comment
while (element.getPreviousSibling() != null) {
Node prev = element.getPreviousSibling();
if (prev.getNodeType() == Node.COMMENT_NODE) {
return prev.getTextContent();
} else if (prev.getNodeType() == Node.TEXT_NODE) {
return getPreviousComment(prev);
} else if (prev.getNodeType() == Node.ELEMENT_NODE) {
return null;
...
String
getPreviousComment(Node element) Gets the previous comment.
while (element.getPreviousSibling() != null) {
Node prev = element.getPreviousSibling();
if (prev.getNodeType() == Node.COMMENT_NODE) {
return prev.getTextContent();
} else if (prev.getNodeType() == Node.TEXT_NODE) {
return getPreviousComment(prev);
} else if (prev.getNodeType() == Node.ELEMENT_NODE) {
return null;
...