I have this string containing my request xml. I want to delete below "id" tags from this string if they exist and return it back. Removing "Identity" completely will also work, if that can be done.
To be deleted :
<Identity>
<id extension="7865232" aan = "BUH"/>
<code/>
</Identity>
<Identity>
<id extension="88769032" aan = "DIH"/>
<code/>
</Identity>
String XMLString= "<request version ="1.0">
<minMatch>
<val>100</val>
</minMatch>
<paramList>
<payLoad display = "Full" type="F">
</payLoad>
<IQC code = "2">
</IQC>
<Control display="Default" type = "D">
</Control>
<member>
<memCode code = "Active"
</memCode>
<id extension="12345" aan="ACC"></id>
<id extension="54321" aan="REQ"></id>
<id extension="554376" aan="PDR"></id>
<id extension="66321" aan="NJQ"></id>
<addr use = "H">
<streetLine>123</streetLine>
<city>POLIS</city>
<state>NY</state>
<postalCode>44321</postalCode>
</addr>
<telecom value = "5543213">
</telecom>
<Person>
<name>
<given>JOHN</given>
<family>BILL</family>
</name>
<GenderCode code ="M" display="Male">
</GenderCode>
<birthime vaue="19651002">
</birthime>
<Identity>
<id extensio="7865232" aan = "BUH"/>
<code/>
</Identity>
<Identity>
<id extensio="88769032" aan = "DIH"/>
<code/>
</Identity>
</Person>
</member>
----
---
</request>"
I am using below code to achieve the same but it's not working and giving me The constructor DOMSource(Document) is undefined. I tired converting document into a byte Array but that's also not working.Is there any way i can simply do this in Java 1.8. Any other approach is also welcome. Please suggest.Thank you!
public void removeIds(String xmlString){
Document doc = null;
SAXBuilder saxbuilder = new SAXBuilder();
try{
doc = saxbuilder.build(new StringReader(xmlString));
}catch(JDOMException je){
je.printStackTrace();
}catch(IOException ie){
ie.printStackTrace();
}
Element rootNode = doc.getRootElement();
IteratorIterable<Element> rootChildren=rootNode.getDescendants(new ElementFilter("Person"));
for(Element Person:rootChildren){
for(Element Identity:Person.getChildren("Identity")){
((Element) doc.getRootElement.getDescendants(new ElementFilter("Identity"))).removeChild("id");
}
}
try{
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer;
transformer = tf.newTransformer();
// transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString();
return output;
} catch (TransformerException e) {
e.printStackTrace();
}
}