How to set an empty value using XPath?

Posted by Ricardo on Stack Overflow See other posts from Stack Overflow or by Ricardo
Published on 2010-04-29T10:55:32Z Indexed on 2010/04/29 11:07 UTC
Read the original article Hit count: 265

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about Xml

Related posts about xpath