Но как это возможно при реализации через поиск по тегу? Какой вариант xml еще проверить, чтобы получить неверный вывод?
package com.javarush.task.task33.task3309;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/*
Комментарий внутри xml
*/
public class Solution {
private static final String XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<first>\n" +
"<second>some string</second>\n" +
"<second>some string</second>\n" +
"<second><![CDATA[need CDATA because of <second>]]></second>\n" +
"<second/>\n" +
"</first>";
public static String toXmlWithComment(Object obj, String tagName, String comment) throws JAXBException, IOException {
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(obj, writer);
String s = writer.toString();//XML;
writer.close();
Document doc = Jsoup.parse(s, "", Parser.xmlParser());
Elements els = doc.select(tagName);
for (Element el : els) {
if (el.tagName().equals(tagName)) {
el.before(String.format("<!--%s-->", comment));
}
}
return doc.toString();
}
public static void main(String[] args) throws JAXBException, IOException {
First first = new First();
first.second.add("1");
first.second.add("2");
first.second.add("3");
System.out.println(toXmlWithComment(first, "gh", "comment"));
}
@XmlRootElement
public static class First {
public List<String> second = new ArrayList<>();
}
}