Don't have any idea how to solve this further, some hints would be appreciated.
package com.codegym.task.task33.task3309;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
/*
Comments inside XML
*/
public class Solution {
public static String toXmlWithComment(Object obj, String tagName, String comment) throws JAXBException {
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(obj, writer);
String xml = writer.toString();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document doc = null;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource(new StringReader(xml)));
} catch (ParserConfigurationException | IOException | SAXException e) {
e.printStackTrace();
}
if (doc != null) {
NodeList nodeList = doc.getElementsByTagName("*");
NodeList seconds = doc.getElementsByTagName(tagName);
if (seconds.getLength() > 0) {
for (int i = 0; i < seconds.getLength(); i++) {
Node secondNode = seconds.item(i);
if (secondNode.getTextContent().contains("CDATA")) continue;
nodeList.item(0).insertBefore(doc.createComment(comment)
, secondNode);
}
}
return docToString(doc);
}
return "";
}
public static void main(String[] args) throws JAXBException {
String xml = toXmlWithComment(new First(), "second", "hey");
System.out.println(xml);
}
private static String docToString(Document doc) {
try {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(doc), new StreamResult(sw));
return sw.toString();
} catch (Exception ex) {
throw new RuntimeException("Error converting to String", ex);
}
}
}