%ARN%

How can I set an empty value using XPath?

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. The code I am using to get the nodes:

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 the value of% ARN%: //// templateitem [@itemid = 5 ] / templateitemdata / text () and using the getNode method , I can get the node and then call getNodeValue ().

Besides getting this value, I would like to set the templateitemdata value for the "templateitem [@itemid = 6 ]" parameter , since it is empty. But the code I am using cannot get Node with it empty. Result is null.

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

+2


a source to share


2 answers


You are simply requesting the node element itself (not its child node):

// templateitem [@ itemid = 6] / templateitemdata


getNodeValue()

works with the node element too, using text()

in XPath, in both cases completely redundant.

+2


a source


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);
}

      

Request for: // templateitem [@itemid = 6] / templateitemdata p>



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 am using setTextContent () instead of setNodeValue ().

0


a source







All Articles