I am trying to update empty node value using xpath.When Node has some value set,its getting updated .but if node value is empty,its not getting updated.
Below is code snippet:
Document document = dBuilder.parse(new File(filename));
document.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/Document/FIToFICstmrCdtTrf/GrpHdr/TtlIntrBkSttlmAmt";
NodeList nodes = (NodeList) xPath.evaluate(expression, document,
XPathConstants.NODESET);
nodes.item(0).setNodeValue("ABC");
This is the right way:
node.appendChild(document.createTextNode("ABC"));
It would be more efficient to fetch a node only instead of the nodelist (if this is the only node):
Node node = (Node) xPath.evaluate(expression, document, XPathConstants.NODE);
You can check the existing value in this ways: 1, if you use your current xpath, you have to check that is there child node or not:
node.getFirstChild() != null // in this case, the node.getFirstChild().getNodeValue() gives back the stored text.
2, or, you can test it in this way:
String expression = "/Document/FIToFICstmrCdtTrf/GrpHdr/TtlIntrBkSttlmAmt/text()";
Node node = (Node) xPath.evaluate(expression, document,
XPathConstants.NODE);
node != null // in this case, the node.getNodeValue() gives back the stored text.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.