I have the below XML. Here I want to get the previous sibling of node c which is b using java
<root>
<a>
<b>
<c>
<d>
</a>
</开发者_开发技巧root>
Whenever I try to get the node using node.getPreviousSibling() method I get the node as #text but not the node b.
Any help on this is very much appreciated.
You need to do something like this: (the #text that you get is the actual text in the node)
public static Element getPreviousSiblingElement(Node node) {
Node prevSibling = node.getPreviousSibling();
while (prevSibling != null) {
if (prevSibling.getNodeType() == Node.ELEMENT_NODE) {
return (Element) prevSibling;
}
prevSibling = prevSibling.getPreviousSibling();
}
return null;
}
You could use a loop...
while (node!= null && !(node instanceOf Element)) {
node = node.getPreviousSibling();
}
You could also use an XPath expression, ./previous-sibling::*
精彩评论