Помогите люди добрые тесткейсом у кого найдется, или советом чего не так в коде.
Прокомментировал основной метод "addComments". Вызывающий метод вроде как у всех.
А не проходит решение в итоге по 3м пунктам. Изучил уже все вопросы и рекомендации в обсуждении, не понимаю в чем ошибка.
Вывод xml похож на правду:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<first>
<!--it's comment-->
<second>some string</second>
<!--it's comment-->
<second>
<![CDATA[need CDATA because of <second>]]>
</second>
<!--it's comment-->
<second/>
<forth>
<!--it's comment-->
<second>some string</second>
<!--it's comment-->
<second>
<![CDATA[need CDATA because of <second>]]>
</second>
</forth>
<fifth>
<![CDATA[need CDATA because of "]]>
</fifth>
</first>
package com.javarush.task.task33.task3309;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
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.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.Queue;
/*
Комментарий внутри xml
*/
public class Solution {
public static String toXmlWithComment(Object obj, String tagName, String comment) {
StringWriter sw = new StringWriter();
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
DocumentBuilder factory = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = factory.newDocument();
marshaller.marshal(obj, doc);
addComments(doc, tagName, comment);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
transformer.transform(new DOMSource(doc), new StreamResult(sw));
} catch (JAXBException | ParserConfigurationException | TransformerException e){
e.printStackTrace();
}
return sw.toString();
}
private static void addComments(Document doc, String tagName,String comment){
Queue<Node> Q = new LinkedList<>();
Q.add(doc.getDocumentElement());//add root
while (!Q.isEmpty()){ // standard bfs
Node node = Q.poll(); //taking node from query
if (node.hasChildNodes()){ //if has children
NodeList childList = node.getChildNodes(); //getting child list
for (int j = 0; j < childList.getLength(); j++){ //iterating through children
Node childNode = childList.item(j); //get child node
if (childNode.getNodeName().equals("#text") && (childList.getLength() == 1) && childNode.getNodeValue().matches(".*[<>&'\"].*")){
// if child - text element and contains specific symbols
node.replaceChild(doc.createCDATASection(childNode.getNodeValue()), childNode); //wrap text into CDATA
} else {
Q.add(childNode); //add child nod to future process
if (childNode.getNodeName().equals(tagName)) { //if tag name - target and inside no CDATA section with target tag
node.insertBefore(doc.createComment(comment), childNode);
j++;
}
}
}
}
}
}
public static void main(String[] args) {
First first = new First();
System.out.println(toXmlWithComment(first, "second", "it's comment"));
}
@XmlRootElement(name = "first")
public static class First {
@XmlElement(name = "second")
public String item1 = "some string";
@XmlElement(name = "second")
public String item2 = "need CDATA because of <second>";
@XmlElement(name = "second")
public String item3 = "";
@XmlElement(name = "third")
public String item4;
@XmlElement(name = "forth")
public Second[] third = new Second[]{new Second()};
@XmlElement(name = "fifth")
public String item5 = "need CDATA because of \"";
}
public static class Second {
@XmlElement(name = "second")
public String item1 = "some string";
@XmlElement(name = "second")
public String item2 = "need CDATA because of <second>";
}
}