This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes XML and Related Technologies and the fly likes HJow to insert nodes using Dom?  Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "HJow to insert nodes using Dom?  " Watch "HJow to insert nodes using Dom?  " New topic
Author

HJow to insert nodes using Dom?

Max Tomlinson
Ranch Hand

Joined: Jul 17, 2001
Posts: 365
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

Joined: Jul 17, 2001
Posts: 365
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());
}
}
 
 
subject: HJow to insert nodes using Dom?
 
Similar Threads
Getting all child element from root element
Problem reading XML
Parsing data out of an XML document
Confusions about a DOM hierarchy
below code is correct way to write the code in generic way if we receive different xml formats