xmlxpathxml-parsingattributesparent-node

How to fetch attribute value of parent node from child nodelist.(XPath)


Here's the requirement

I have a xml document which looks something like this

-<page height="777" width="777">
    -<block r="777" l="777" blockType="Separator">
        +<region>
        +<separator>
    -<block r="777" l="777" blockType="Separator">
        +<region>
        +<separator>
    -<block r="777" l="777" blockType="Text">
        +<region>
        +<text>
</page>     

I have all the separator blocks in separatorNodeList

    String expression = "//page/block/separator";
    XPathExpression expr = xPath.compile(expression);
    NodeList separatorNodeList = (NodeList) expr.evaluate(xmlDocument, XPathConstants.NODESET);

Now, i am trying to get the attribute(r,l) value of parent node of separator block.i.e. something like

int separatorDistanceFromRight = Integer.parseInt(((Element)separatorNodeList.item(i)).getParentNode().getAttribute("r"));

But the above doesn't seem to work. Any Quick help ??


Solution

  • Ahh,i found this.

    int separatorDistanceFromRight = Integer.parseInt(separatorNodeList.item(i).getParentNode().getAttributes().getNamedItem("r").getNodeValue());