I think the best to do when you have to manipulate a DOM in memory and querying in it, is to work with XPath. With XPath you can reach easily the node you are looking for and after you can manipulate it.
This is an example for removing a node:
****
Node aNode = ... result of an XPath query ...
Node parentNode = aNode.getParentNode();
parent.removeChild(aNode);
****
This is an example of a function for retrieving a list of nodes belonging to an XPath expression. This example works with Xalan.
public NodeList findNode(Document
doc,
String query) throws SAXException {
// query = xpath expression
// doc = the DOM object representing the XML document you want manipulate.
XPath xPath = new XPath();
XPathSupport xpathSupport = new XMLParserLiaisonDefault();
XPathProcessorImpl parser = new XPathProcessorImpl(xpathSupport);
PrefixResolverDefault prefixResolver = new PrefixResolverDefault(doc.getDocumentElement());
parser.initXPath(xPath, query, prefixResolver);
XObject xObject = xPath.execute(xpathSupport, doc.getDocumentElement(), prefixResolver);
return xObject.nodeset();
}