开发者

java XML find the sibling node

开发者 https://www.devze.com 2023-04-06 06:23 出处:网络
I have the below XML. Here I want to get the previous sibling of node c which is b using java <root>

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::*

0

精彩评论

暂无评论...
验证码 换一张
取 消