How to check if node has siblings?

I have an org.w3c.dom.Node object.

I would like to see if he has other brothers and sisters.

Here is what I tried:

Node sibling = node.getNextSibling();
if(sibling == null)
    return true;
else
    return false;

HOWEVER, for some reason (possibly due to identification or spaces in the source XML), I am not getting the expected result.

[Besides

 node.getParentNode().getChildNodes().getLength() 

gives a value higher than I expected.]

I welcome your suggestions for improving this code.

EDIT

As shown below, the empty nodes seem to interfere with my attempts to count brothers and sisters.

xml looks something like this:

  <a>
        <b>
              <c>I have this node:</c>
              <c>I want to know how many of these there are.</c>
              <c>This is another sibling.</c>
        </b>
        <b>
        </b>

  </a>

Starting from my node (first <c> </c> above), how do I find out the number of other siblings?

+3
source share
4 answers

node, . Element, . Element. , getChildNodes, , ELEMENT_NODE.

, :

public function isSingleChild(Node node) {
    boolean singleChild = true;
    NodeList siblings = node.getParentNode().getChildNodes();
    for(int i = 0, int len = siblings.getLength(); i < len; i++) {
        if(siblings.item(i).getNodeType() == Node.ELEMENT_NODE) {
            singleChild = false;
            break;
        }
    }

    return singleChild;
}

, , node:

<div>
    <!-- Comment Node -->
    <p>Element node</p>
    a text node
</div>

div childNodes 3 , node, " Node", node "P" node " Node".

+3

. ( , , , , , ).

java , , .

+2

Java, # , , , XPath:

bool hasSiblings = elm.SelectNodes("../*").Count == 1;

* , , "node" , node, . ( 90% , - XML, "node", "".)

+1

.

, , seanmonstar.

public Boolean isSingleChild(Node node)
{
    int elementNodes = 0;
    NodeList siblings = node.getParentNode().getChildNodes();
    for(int x = 0 ; x < siblings.getLength(); x++)
    {
        if(siblings.item(x).getNodeType() == Node.ELEMENT_NODE)
        {
            elementNodes++;
        }
    }
    if(elementNodes == 1)
         return true;
    else
        return false;
}
0

Source: https://habr.com/ru/post/1722359/


All Articles