File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
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());
}
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: HJow to insert nodes using Dom?
 
Similar Threads
Problem reading XML
Confusions about a DOM hierarchy
Parsing data out of an XML document
below code is correct way to write the code in generic way if we receive different xml formats
Getting all child element from root element