Java convert XML to YAML - java

I need to convert a XML File to YAML.
I could not find anything helpful on Google.
Is there any similar API like the json in java to convert a XML file to YAML?

You could use Jackson, it supports XML and YAML (and also JSON, CSV and more).
https://github.com/FasterXML/jackson-dataformat-xml
https://github.com/FasterXML/jackson-dataformat-yaml
Or if it's more easy to understand for you, take two steps: XML -> JSON , JSON -> YAML. Because there are lot's of tutorials for XML -> JSON and YAML is pretty similar to JSON.

Other than json, you can use TestNG to convert XML to YAML,
http://testng.org/javadoc/org/testng/Converter.html
http://www.infoq.com/news/2011/03/testng-60

You may combine underscore-java and snakeyaml libraries.
Steps:
Read xml file to map.
Generate yml file from map.
import com.github.underscore.lodash.Xml;
import java.io.StringWriter;
import org.yaml.snakeyaml.Yaml;
Object result = Xml.fromXml(xml);
Yaml yaml = new Yaml();
StringWriter stringWriter = new StringWriter();
yaml.dump(result, stringWriter);
String yaml = stringWriter.toString();

Related

Read a toml file in java 2022

After a quick research, I found the following three libraries for parsing Toml files in java.
toml4j
tomlj
jackson-dataformats-text
What I am looking for is a library that can parse toml files without a corresponding POJO class. While both toml4j, and tomlj can achieve that, they do not seem to be maintained.
jackson-dataformats-text on the other is actively maintained but I can not parse a toml file without the corresponding POJO class.
Is there a way to create a dynamic class in java that I can use to parse any toml file?
If you just need to read a TOML file without a POJO, FasterXML Jackson libraries are a great choice. The simplest method is to just read the content as a java.util.Map:
final var tomlMapper = new TomlMapper();
final var data = tomlMapper.readValue(new File("config.toml"), Map.class);
After that, the content of the file will be available in data.
If you need even lower level parsing, all formats supported by FasterXML Jackson can be read using the stream API. In case you need that, read about the stream API on the core module: FasterXML/jackson-core, just make sure you use the right factory class (TomlFactory instead of JsonFactory).

Reading YAML in Java without boiler plate

I was wondering if there is a way to read a YAML file in Java without having to create a lot of POJO's but still have the ability to cleanly read the elements of the YAML. Meaning, not messing with LinkedHashmaps.
Is there a library or something that can do this?
Thanks in advance
Regards
You can use Jackson library, the ObjectMapper (the most important class of that library) has a method readTree which returns a JsonNode, which you can read and traverse. Usage is pretty simple:
String yamlString =
"---\n" +
"name: Bob\n" +
"age: 35";
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
JsonNode root = mapper.readTree(yamlString);
String name = root.get("name").asText();
int age = root.get("age").asInt();
Make sure you check some tutorials and don't get confused if you find too much stuff about JSON, because Jackson has been originally a library parsing JSON, other formats were added later.

How to convert any input XML file to similar Java object structure?

Hi all can any one tell me is it possible to convert any XML file file to equivalent java object using java?
You want a DOM parser. There are many around, a Google search for "Java DOM parser" will help you. Take this page for example.
You are probably looking for JAXB.
Use XStream library it is quite simple:
http://x-stream.github.io/tutorial.html
// object -> XML -> File
XStream xstream = new XStream(driver);
String data = xstream.toXML(metaData);
// XML -> object
XStream xstream = new XStream(new JettisonMappedXmlDriver());
YourClass obj = (UourClass)xstream.fromXML(jSON);
You could use unmarshall function in castor.
Let me add another to the collection.
Have a look at the Apache Jakarta Digester this is what Tomcat uses to automap XML files (like server.xml).

How to read an XML file with Java?

I don't need to read complex XML files. I just want to read the following configuration file with a simplest XML reader
<config>
<db-host>localhost</db-host>
<db-port>3306</db-port>
<db-username>root</db-username>
<db-password>root</db-password>
<db-name>cash</db-name>
</config>
How to read the above XML file with a XML reader through Java?
I like jdom:
SAXBuilder parser = new SAXBuilder();
Document docConfig = parser.build("config.xml");
Element elConfig = docConfig.getRootElement();
String host = elConfig.getChildText("host");
Since you want to parse config files, I think commons-configuration would be the best solution.
Commons Configuration provides a generic configuration interface which enables a Java application to read configuration data from a variety of sources (including XML)
You could use a simple DOM parser to read the xml representation.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse("config.xml");
If you just need a simple solution that's included with the Java SDK (since 5.0), check out the XPath package. I'm sure others perform better, but this was all I needed. Here's an example:
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
...
try {
XPath xpath = XPathFactory.newInstance().newXPath();
InputSource inputSource = new InputSource("strings.xml");
// result will equal "Save My Changes" (see XML below)
String result = xpath.evaluate("//string", inputSource);
}
catch(XPathExpressionException e) {
// do something
}
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="saveLabel">Save My Changes</string>
</resources>
There are several XML parsers for Java. One I've used and found particularly developer friendly is JDOM. And by developer friendly, I mean "java oriented" (i.e., you work with objects in your program), instead of "document oriented", as some other tools are.
I would recommend Commons Digester, which allows you to parse a file without writing reams of code. It uses a series of rules to determine what action is should perform when encountering a given element or attribute (a typical rule might be to create a particular business object).
For a similar use case in my application I used JaxB. With Jaxb, reading XML files is like interacting with Java POJOs. But to use JAXB you need to have the xsd for this xml file. You can look for more info here
If you want to be able to read and write objects to XML directly, you can use XStream
Although I have not tried XPath yet as it has just come to my attention now, I have tried a few solutions and have not found anything that works for this scenario.
I decided to make a library that fulfills this need as long as you are working under the assumptions mentioned in the readme. It has the advantage that it uses SAX to parse the entire file and return it to the user in the form of a map so you can lookup values as key -> value.
https://github.com/daaso-consultancy/ConciseXMLParser
If something is missing kindly inform me of the missing item as I only develop it based on the needs of others and myself.

Converting a raw file (binary data ) into XML file

I'm working on a project under which i have to take a raw file from the server and convert it into XML file.
Is there any tool available in java which can help me to accomplish this task like JAXP can be used to parse the XML document ?
I guess you will need your objects for later use ,so create MyObject that will be some bean that you will load the values form your Raw File and you can write this to someFile.xml
FileOutputStream os = new FileOutputStream("someFile.xml");
XMLEncoder encoder = new XMLEncoder(os);
MyObject p = new MyObject();
p.setFirstName("Mite");
encoder.writeObject(p);
encoder.close();
Or you con go with TransformerFactory if you don't need the objects for latter use.
Yes. This assumes that the text in the raw file is already XML.
You start with the DocumentBuilderFactory to get a DocumentBuilder, and then you can use its parse() method to turn an input stream into a Document, which is an internal XML representation.
If the raw file contains something other than XML, you'll want to scan it somehow (your own code here) and use the stuff you find to build up from an empty Document.
I then usually use a Transformer from a TransformerFactory to convert the Document into XML text in a file, but there may be a simpler way.
JAXP can also be used to create a new, empty document:
Document dom = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.newDocument();
Then you can use that Document to create elements, and append them as needed:
Element root = dom.createElement("root");
dom.appendChild(root);
But, as Jørn noted in a comment to your question, it all depends on what you want to do with this "raw" file: how should it be turned into XML. And only you know that.
I think if you try to load it in an XmlDocument this will be fine

Categories

Resources