Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HJow to insert nodes using Dom?

 
Max Tomlinson
Ranch Hand
Posts: 365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all-
I'm trying to insert some nodes using DocumentBuilderFactory.

wheat i am trying to do is insert <long>123</long>
into a <list> element

This is a document I have read from file and have parsed.

NodeList nl = doc.getElementsByTagNameNS(qns, "list");
if (nl.getLength()>0){
Node n = nl.item(0).getLastChild();
Iterator<String> it = notifications.iterator();
while (it.hasNext()) {
Node idNode = doc.createElementNS(qns, "long");
idNode.setNodeValue(it.next());
n.appendChild(idNode);
log.info("ID Node appended to query list: " + idNode.getNodeValue());
}
} else {
log.error("Empty nodelist from " + fn + " for '(query) list'");
}

I get an exception on the add (insert) HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.

many thanks
Max
 
Max Tomlinson
Ranch Hand
Posts: 365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I answered my own question:

DocumentBuilder db = dbf.newDocumentBuilder();
//String fn = dir+this.findReviewUpdateReqFile;
log("parsing file for update " + fn);
Document doc = db.parse(fn);
NodeList ol = doc.getElementsByTagName("quer:long");
int len = ol.getLength();
for (int i=len;i>0;i--) {
Node o = ol.item(i-1);
o.getParentNode().removeChild(o);
}

NodeList nl = doc.getElementsByTagName("quer:list");
if (nl.getLength()>0){
Node n = nl.item(0);
Iterator<String> it = notifications.iterator();
while (it.hasNext()) {
String val = it.next();

Element element = doc.createElement("quer:long");

element.appendChild(doc.createTextNode(val));
n.appendChild(element);
log("ID Node appended to query list: " + element.getNodeValue());
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic