tags:

views:

56

answers:

2

Using this xml example:

<templateitem itemid="5">
   <templateitemdata>%ARN%</templateitemdata>
</templateitem>
<templateitem itemid="6">
   <templateitemdata></templateitemdata>
</templateitem>

I am using XPath to get and set Node values. The code I am using to get the nodes is:

private static Node ***getNode***(Document doc, String XPathQuery) throws XPathExpressionException
{
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile(XPathQuery);
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    if(nodes != null && nodes.getLength() >0)
        return nodes.item(0);
    throw new XPathExpressionException("No node list found for " + XPathQuery);
}

To get %ARN% value: "//templateitem[@itemid=5]/templateitemdata/text()" and with the getNode method I can get the node, and then call the getNodeValue().

Besides getting that value, I would like to set templateitemdata value for the "templateitem[@itemid=6]" since its empty. But the code I use can't get the node since its empty. The result is null.

Do you know a way get the node so I can set the value?

+1  A: 

You simply ask for the element node itself (not for its child text node):

//templateitem[@itemid=6]/templateitemdata

getNodeValue() works on an element node as well, using text() in the XPath is completely superfluous, in both cases.

Tomalak
A: 

I changed the method for:

public static Node getNode(Document doc, String XPathQuery) throws XPathExpressionException
{
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile(XPathQuery);
    Object result = expr.evaluate(doc, XPathConstants.NODE);
    Node node = (Node) result;
    if(node != null )
        return node;
    throw new XPathExpressionException("No node list found for " + XPathQuery);
}

The query for: //templateitem[@itemid=6]/templateitemdata

And the setValue method for:

public static void setValue(final Document doc, final String XPathQuery, final String value) throws XPathExpressionException
{
    Node node = getNode(doc, XPathQuery);
     if(node!= null)
             node.setTextContent(value);
     else
         throw new XPathExpressionException("No node found for " + XPathQuery);
}

I use setTextContent() instead setNodeValue().

Ricardo