How to delete a XML tag from XML file without Hard coding the tag Name


I need to delete all <strong>OBJECT</strong> TAG in XML file using Java. I can able to delete the <strong>OBJECT</strong> Tag when I enter parent Tag Name(<strong>SPAN</strong>) directly Hard code into the source code("span"), But I need to delete the Tag without hard code Parent Tag. If I hard code, I can able to delete only the <strong>Object Tag</strong> inside <strong>span</strong> Tag. I need to <strong>delete</strong> all the <strong></strong> in XML even it may be inside another parent Tag, Without <strong>Hard code</strong> the Parent tag in Source code. I need to delete all <strong>Object</strong> tag available inside both <strong>span</strong> tag and also <strong>score</strong> tag in Sample XML File. For Sample XML File view the below <strong>Image</strong>.

Java Program

public class XmlObject { public static void main(String[] args) { String filePath = "/Users/myXml/Sample.xml"; File xmlFile = new File(filePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; try { dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); deleteElement(doc); doc.getDocumentElement().normalize(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("/Users/myXml/Sample_ObjDelete.xml")); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(source, result); System.out.println("XML file updated successfully"); } catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) { e1.printStackTrace(); } } private static void deleteElement(Document doc) { NodeList RootElement = doc.getElementsByTagName("assessmentItem"); int getRootElementLength = RootElement.getLength(); System.out.println("getRootElementLength "+getRootElementLength); for(int k = 0; k < getRootElementLength; k++){ System.out.println("2"); Node nNode = RootElement.item(0); Element eElement = (Element) nNode; NodeList object = eElement.getElementsByTagName("span"); Element obj = null; for(int i=0; i<object.getLength();i++){ obj = (Element) object.item(i); int leng = obj.getElementsByTagName("object").getLength(); System.out.println("object:" +leng); for(int j=0; j<leng;j++){ Node objectNode = obj.getElementsByTagName("object").item(k); (obj).removeChild(objectNode); } } } } }

<pre class="snippet-code-html lang-html prettyprint-override"><qualityTest> <responseDeclaration> <correctResponse> <value>QualityTest</value> </correctResponse> </responseDeclaration> <itemBody> <sampleTest>

Who is president of uganda?</P> <span> <object> Yoweri Museveni</object> <span> <object> Raúl Castro </Object> </span> </sampleTest> </itemBody> <score> <object> Yingluck Shinawatra </Object> </score> </qualityTest>


You should walk the xml-tree recursively and remove all occurencies of any object element:

private static void deleteElement(Node someNode) { NodeList childs = someNode.getChildNodes(); for (int i = 0; i < childs.getLength();) { Node child = childs.item(i); if (child.getNodeType() == Document.ELEMENT_NODE) { if (child.getNodeName().equalsIgnoreCase("object")) { child.getParentNode().removeChild(child); continue; } else { deleteElement(child); } } i++; } }

This little code snippet will remove any xml-tag named "object" in any depth of the tree.


You can use Xpath and XpathExpression for going <strong>Span</strong> and <strong>Score</strong> tags

XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "//span"; NodeList spanNodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);

spanNodeList will give you all span nodes. so you iterate the spanNodeList and delete the span element like below code

for (int i = 0; i < spanNodeList .getLength(); i++) { Node spanItem= spanNodeList .item(i); Node parentNode = spanItem.getParentNode(); parentNode.removeChild(spanItem); }

and same for <strong>Score</strong> tag also


You can use an XPath to select all elements except <object> elements. For instance, you can put this in a file named strip-object.xsl:

<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" omit-xml-declaration="yes"/> <xsl:template match="//object"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>

Notice the first template rule, which does nothing with object nodes, effectively discarding them. The second template rule, which takes effect for all other nodes, copies them exactly.

To make use of it, initialize your Transformer with the .xsl file:

Transformer transformer = transformerFactory.newTransformer( new StreamSource(new File("/Users/myXml/strip-object.xsl")));

If you only want to strip out object elements which are children of span and score elements, you can change the XPath expression:

<xsl:template match="//span/object|//score/object"/>


  • Java format xml using Transformer with CDATA part
  • XML get all nodes with the same name
  • Validate AND read with the same inputstream
  • How to tell Xalan to escape characters in HTML attributes
  • Retrieve RSS feed and display it in text view
  • org.xml.sax.SAXException: Bad envelope tag: definitions
  • XSLT sort edge case for ascending sort by element name
  • auto indent code in html file (generator/tool)?
  • Python: Facebook Graph API - pagination request using facebook-sdk
  • in node.js, how to pass variables to :stylus filter from jade?
  • Why is YAML.load returning the wrong numeric value?
  • Compare Date & Time Javascript
  • Anonymous functions and Maps in Scala
  • getting bad request while using passport in login form
  • Class works not correct. How to make it better?
  • CodeIgniter - Autoload
  • How can we extract the main verb from a sentence?
  • ANTLR4: Unrecognized constant value in a lexer command
  • Python: how to split and return a list from a function to avoid memory error
  • css Star-rating html
  • How to parse Java properties which contains variables?
  • How can I apply differnt styles when transforming data using json2html based on data value?
  • Implicit property animations do not work with CAReplicatorLayer?
  • Change the width of the JQM panels
  • Treetop basic parsing and regular expression usage
  • What's a fast (non-loop) way to apply a dict to a ndarray (meaning use elements as keys and rep
  • Regex for Specific Tag
  • Is it possible to run clang with llc flags
  • Adding elements to a huge XML file
  • App restarts from wrong activity
  • How integrated is Collada to OpenGL ES
  • Jackson Parser: ignore deserializing for type mismatch
  • Jetty Server not starting: Unable to establish loopback connection
  • Array.prototype.includes - not transformed with babel
  • Validaiting emails with Net.Mail MailAddress
  • sending/ receiving email in Java
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Proper folder structure for lots of source files
  • How does Linux kernel interrupt the application?