Here I am going to explain how to remove node from XML file.
Step 1) Here I have an XML string like this
<Transaction>
<ComponentDetails>
<Status new="Dhina"/>
</ComponentDetails>
</Transaction>
try
{
//Remove node from xml
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
Element element = (Element) doc.getElementsByTagName("Status").item(0);
if (element.getAttribute("new").equals("Dhina")) {
element.getParentNode().removeChild(element);
}
doc.normalize();
//Converting Document to String
Transformer tf =TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
Writer out = new StringWriter();
tf.transform(new DOMSource(doc), new StreamResult(out));
Toast.makeText(getApplicationContext(),out.toString(),Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
Final Output will be like this
<Transaction>
<ComponentDetails>
</ComponentDetails>
</Transaction>
Happy Coding:)
No comments:
Post a Comment