We would like to know how to remove element from parent.
/*from ww w. j ava 2 s. co m*/ import java.io.StringReader; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; public class Main { public static String getXMLData(){ return "<a><img/><x></x></a>"; } public static void main(String[] argv) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(getXMLData()))); Element element = (Element) doc.getElementsByTagName("x").item(0); Node parent = element.getParentNode(); parent.removeChild(element); parent.normalize(); System.out.println(parent); } }
The code above generates the following result.