Валидатор ни в какую не пропускает пункт 3 и 5 задачи.
3. Метод не должен изменять входящий xml в случае, если искомый тег отсутствует в нем.
5. все вместе взятое
Как должен выглядеть пример неизменяемого файла? Выводить как при обычном маршалинге, без коментов и замен CDATA.
Буду рада, если кто подскажет, целый день танцы с валидатором.
package com.javarush.task.task33.task3309;
import org.w3c.dom.*;
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.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
;
/*
Комментарий внутри xml
*/
public class Solution {
public static String toXmlWithComment(Object obj, String tagName, String comment) throws JAXBException,
ParserConfigurationException,
TransformerException, IOException, SAXException {
// Create marshall object
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setCoalescing(true); // specifies that parser produced by this code will convert CDATA nodes to text
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
// Convert object to document
// doc.setXmlStandalone(false);
marshaller.marshal(obj, doc);
//Output the document
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // this allows you make \n
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
NodeList nodeList = doc.getElementsByTagName(tagName);
if (doc.getElementsByTagName(tagName).getLength() > 0) {
for (int i = 0; i < nodeList.getLength(); i++) {
if (nodeList.item(i).getNodeName().equals(tagName)) {
nodeList.item(i).getParentNode().insertBefore(doc.createComment(comment), nodeList.item(i));
if (nodeList.item(i).getFirstChild().getNodeType() == Node.TEXT_NODE) {
Node thisNode = nodeList.item(i).getFirstChild();
if (thisNode.getTextContent().matches(".*[<>&\'\"].*")) {
String content = thisNode.getTextContent();
CDATASection cdataSection = doc.createCDATASection(content);
nodeList.item(i).replaceChild(cdataSection, thisNode);
}
}
}
}
}
// Convert doc to string
StringWriter write = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(write));
return write.toString();
}
public static void main(String[] args) throws JAXBException, ParserConfigurationException, TransformerException, IOException, SAXException {
System.out.println(toXmlWithComment(new First(), "nothing", "it's a comment"));
System.out.println("--------------------------------------------------------------------------------------------------------------------");
System.out.println(toXmlWithComment(new First(), "second", "it's a comment"));
}
}