I want to remove child element from xml.
My XML file is
<mcss>
<quest ans="0">
<question><![CDATA[ This is question one]]></question>
<options>
<option><![CDATA[B<Option one]]></option>
<option><![CDATA[B<Option second]]></option>
<option><![CDATA[B<Option three]]></option>
</options>
<explaination><![CDATA[explaination one]]></explaination>
</quest>
<quest ans="0">
<question><![CDATA[ This is question two]]></question>
<options>
<option><![CDATA[B<Option one]]></option>
<option><![CDATA[B<Option second]]></option>
<option><![CDATA[B<Option three]]></option>
</options>
<explaination><![CDATA[explaination two]]></explaination>
</quest>
</mcss>
if I want to remove question first the how can i do? output XML..
<?xml version="1.0" encoding="UTF-8"?>
<mcss>
<quest ans="0">
<question><![CDATA[ This is question two]]></question>
<options>
<option><![CDATA[B<Option one]]></option>
<option><![CDATA[B<Option second]]></option>
<option><![CDATA[B<Option three]]></option>
</options>
<explaination><![CDATA[explaination two]]></explaination>
</quest>
</mcss>
My java Code to remove question one.
String path="D://test//N2074_set2.xml";
File structureXml = new File(path);
SAXBuilder saxb = new SAXBuilder();
Document document = saxb.build(structureXml);
Element rootElement = document.getRootElement();
XMLOutputter xmlOutput = new XMLOutputter();
for (int i = 0; i < qestList.size(); i++) {
Element quesList = (Element) qestList.get(2);
if(quesList.getName().equalsIgnoreCase("quest"))
rootElement.removeContent(2);
}
FileOutputStream file=new FileOutputStream(path);
xmlOutput.output(document, file);
I think you have missed an easy solution to the problem. If you have any JDOM Content (Element, Attributed, Text, etc.), you can remove it from its parent using the
detach()
method. In your case though, you may want to use an Iterator to go through the Child Elements of the root node, and then remove the matching content from the Iterator.... :Note that you cannot use detach() inside an iterator because that will cause a ConcurrentModificationException.