Alternatively, you could use the XPath
capabilities in the JDK
to find the label
element with comment and then remove it from its parent:
// I took the xml sample as an example.
String source =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<Translations xmlns=\"http:...\">\n" +
" <customApplications>\n" +
" <label><!-- Pricing Notifications --></label>\n" +
" <name>TEAM_Tesla</name>\n" +
" </customApplications>\n" +
" <customApplications>\n" +
" <label><!-- CRM --></label>\n" +
" <name>TEAM_Tender</name>\n" +
" </customApplications>\n" +
" <customApplications>\n" +
" <label>Actualization Portal</label>\n" +
" <name>Actualization_Portal</name>\n" +
" </customApplications>\n" +
"</Translations>";
// We are converting the xml into a document.
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(source));
Document document = documentBuilder.parse(inputSource);
// Evaluate expression result on xml document.
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
String xpathExpression = "//*//*//label[descendant::comment()]//parent::customApplications";
XPathExpression xPathExpression = xpath.compile(xpathExpression);
NodeList nodes = (NodeList) xPathExpression.evaluate(document, XPathConstants.NODESET);
// Process of removing the nodes you find.
for (int i = 0; i < nodes.getLength(); i++) {
nodes.item(i).getParentNode().removeChild(nodes.item(i));
}
// Transformer to console.
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(System.out));
If you want to output to a file:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(new File("output.xml"));
Source input = new DOMSource(document);
transformer.transform(input, output);