import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
public class JsonToYamlConverter {
public static String convertJsonToYaml(String json) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper = objectMapper.enable(SerializationFeature.INDENT_OUTPUT).setSerializationInclusion(JsonInclude.Include.NON_NULL).setFactory(new YAMLFactory());
Object jsonObject = objectMapper.readValue(json, Object.class);
return objectMapper.writeValueAsString(jsonObject);
}
}
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
public class XmlToYamlConverter {
public static String convertXmlToYaml(String xmlFilePath) throws Exception {
File xmlFile = new File(xmlFilePath);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
Element root = doc.getDocumentElement();
StringBuilder yamlBuilder = new StringBuilder();
convertElementToYaml(root, yamlBuilder, 0);
return yamlBuilder.toString();
}
private static void convertElementToYaml(Element element, StringBuilder yamlBuilder, int indentation) {
yamlBuilder.append(getIndentation(indentation));
yamlBuilder.append(element.getTagName()).append(":");
NodeList children = element.getChildNodes();
if (children.getLength() > 0) {
yamlBuilder.append("
");
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child instanceof Element) {
convertElementToYaml((Element) child, yamlBuilder, indentation + 1);
}
}
} else {
yamlBuilder.append(" ").append(element.getTextContent()).append("
");
}
}
private static String getIndentation(int indentation) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indentation; i++) {
sb.append(" ");
}
return sb.toString();
}
}