I need to create some XML programmatically, sometimes with programming calls, sometimes starting by reading in some XML (a string) and then revising it with calls. And then write the XML out to a stream.
The writing out I assume is best done with codehaus stax (if there's a newer way, please tell me what). But for the rest, at present I am using dom4j and that is old and abandoned. So I need to upgrade to something that is supported and has no security issues.
Is there something in the Java runtime? Or is there a commonly used library?
We are on Java 1.8 so a solution cannot require 1.9 or later.
You have a lot of options here.
Parsers
Parsers take the whole document (SAX parsed is exception here) and create a tree structure from some common classes like Document, Node etc.. You can load any XML and work with it. No need to have some class that would represent the file.
Pros
you can load any file
you have the power of all the standard XML tooling, like XSLT transformations, xpath, etc..
Cons
hard to create new file programaticaly
harder to extract info from it
Tools
DOM Parsers
SAX Parser
Object serialization
Second approach you can take is by Object parsing. You basically have a class that represents you data structure and you serialize it to/from XML.
Pros
super easy to use
fast to just read/write data from existing data structures
Cons
not easy to use XSLT, etc..
cannot really read random XML files
Tools
JAXB
XStream
Jackson
I am looking for a easy to implement xml to java binding. The problem I am facing that there is more than one xml file, and I need to create one object tree from these files.
JAXB is not helping for two reason : the xmls are not usually have any schema, and second JAXB does not offer any solution for combining them.
I tried smooks too, but it also doesn't offer any multiple XML digestion system.
Does anybody have any idea?
You can do this in JAXB using an initialized XmlAdapter. Below is a link to answer I gave to a similar question:
Using JAXB to cross reference XmlIDs from two XML files
Note:
JAXB implementations (Metro, EclipseLink MOXy, Apache JaxMe) do not require an XML schema:
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
If you use JAXB, I suggest creating your own XSDs for the XML files your need to use. That'll help you document what you thought the schema was at the time, and help identify any future issues due to change at the source.
Then, create a class or classes that deserialize the individual documents into the JAXB-generated classes and then build the object you want from those objects.
Even if you don't use JAXB, I'd still recommend using this kind of pattern to isolate the transformation from XML to Java and keep the part of your app that knows about XML in one place, away from your business logic.
I've used XMLBeans before. Really easy and flexible to use, should be able to help you a great deal.
I have an xml file format and using that xml I want to create skeleton classes needed to serialize and de-serialize that xml. I am using Java and XStream for this.
There is tool in .net world which creates classes using xml. Is there anything similar in Java world?
I have not used XStream myself, so this solution may not 100% work for you. However, the simplest approach in Java is to use Java's Architectural Binding for XML (JAXB) API and tools. JAXB was included as part of the JDK with the release of Java 6. To generate Java code from an XML schema you would use the xjc command that comes with the JDK. Here is an example:
> xjc schemas\my-schema.xsd -d src\java -p com.company.model
This code generation method will create Java Objects that include JAXB-specific annotations that are used by the Marshaller to map the Java object to its XML format and vice versa. It will also contain number of warnings stating that the code was auto-generated and should not be modified. As long as you are not trying to automatically keep the code in synch with your XML you could ignore these messages.
Now, as I mentioned, this technique does generate JAXB annotated classes, however, the generated code may still be compatible with XStream as I believe XStream uses simple attribute name -> xml node name conversion logic.
Have a requirement so want to check its feasibility.We are using JAXB 2.x for unmarshling XML in to out existing POJO classes.below is the process we are following..
Based on the XSD provided we have already created required classes using JAXB utility.
On Run time we are passing only XML file and we first validating the XML with the preexisting XSD and if success than will move ahead with the Unmarshling.
For XML creation same process but in reverse order.
Now there is one requirement so the client want that they can pass XML and XSD to the method being developed and this method should hand over the common object as return by parsing that XML and later on they will handle the process of mapping that generic Object with the specific classes.
My question is,Is it possible in Jaxb 2.x that based on the XSD supplied it will first create required classes on the fly and than will parse XML and hand over the result to the client module so they can do the mapping work or is there any way to achieve that functionality??
Thanks in advance
In EclipseLink MOXy (I'm the tech lead) we have a feature called Dynamic JAXB, that lets you bootstrap from an XML schema and use generic objects. You might find this approach useful:
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/Dynamic
Dynamic java bean from xsd
I know it Is doable. One student in my lab did almost the same thing on a different subject. Though, you will have to play with classloader to be able to load dynamically the classes you've jest created. Once that is done, you can parse the XML using the classloader that includes the new classes.
Of course, it is not as easy as it sounds like...
Have a look at the sample samples/inline-customize
located at http://download.oracle.com/docs/cd/E17802_01/webservices/webservices/docs/2.0/jaxb/samples.html
What's the simplest-to-use techonlogy available to save an arbitrary Java object graph as an XML file (and to be able to rehydrate the objects later)?
The easiest way here is to serialize the object graph.
Java 1.4 has built in support for serialization as XML.
A solution I have used successfully is XStream (http://x-stream.github.io/)- it's a small library that will easily allow you to serialize and deserialize to and from XML.
The downside is you can only very limited define the resulting XML; which might not be neccessary in your case.
Apache digester is fairly easy: http://commons.apache.org/digester/
JAXB is newer and comes with annotation goodness: https://jaxb.dev.java.net
XStream by the folks at Thoughtworks has a simple API and even deals with things like duplicate and circular references. It seems to be actively developed and is well documented.
http://x-stream.github.io/
Use java.beans.XMLEncoder. Its API is very simple (actually a little too simple; it'd be nice to wire it to a SAX ContentHandler), but it works on many graphs out of the box, and it's easy to create your own persistence delegate for any odd-ball classes you might encounter.
The syntax used by XMLDecoder allows
you to invoke any method, instance
or static, including constructors,
so it's extremely flexible.
Other encoders name
elements and attributes after class
and field names, so there's no fixed schema for the result. The XMLEncoder's
XML follows a simple DTD and can
easily be validated or transformed,
even when you've never seen the
types it uses.
You can assign objects an
identifier, and reference them
throughout the graph.
You can refer to constants defined
in classes or interfaces.
And, it's built into Java SE, so you don't need to ship an extra library.
Simple
Although XStream and JAXB can serialize an some object graphs succssfully they can not handle very complex graphs. The most powerful solution for large complex graphs is Simple XML Serialization. It can handle any graph. Also, it’s fast and simple to use without any dependencies.
To quote the Simple project page:
Simple is a high performance XML serialization and configuration framework for Java. Its goal is to provide an XML framework that enables rapid development of XML configuration and communication systems. This framework aids the development of XML systems with minimal effort and reduced errors. It offers full object serialization and deserialization, maintaining each reference encountered. In essence it is similar to C# XML serialization for the Java platform, but offers additional features for interception and manipulation.
The Simple API is, well, simple! It's really good. http://simple.sourceforge.net/
You can also use XStream: http://www.ibm.com/developerworks/library/x-xstream/index.html
JAX-B is part of the standard APIs and really easy to use.
If you need control over the XML that gets generated, I recommend taking a look at Betwixt (http://commons.apache.org/betwixt/) - it adds a lot of functionality to Apache's digester (Digester is good for building object graphs from XML, but is not so good for generating them).
If you really don't care about the XML that gets generated (just that it can be deserialized in the future), then the XMLEncoder/Decoder classes built into Java or good - as long as the objects you are serializing follow the JavaBean specification. The biggest area I've run into problems with the XMLEncoder/Decoder solution is if you have a bean that returns an immutable list for one of it's properties - the encoder doesn't handle that situation very well.
If you need to control the structure of the XML, the XStream is a good choice. You can use annotations to define precisely the structure/mapping of the XML and your objects.
I'd second (or third) XStream. It reads and writes XML without needing any special binding configuration or placing lots of extraneous syntax in the XML.
I put together a list with a lot of xml serialization libraries and its license
XStream is very simple http://x-stream.github.io/
XStream is a simple library to serialize objects to XML and back again.
java.beans.XMLEncoder perhaps?
Jackson
The Jackson Project is a processing and binding library for XML, JSON, and some other formats.
… Jackson is a suite of data-processing tools for Java (and the JVM platform), including the flagship streaming JSON parser / generator library, matching data-binding library (POJOs to and from JSON) and additional data format modules to process data encoded in Avro, BSON, CBOR, CSV, Smile, (Java) Properties, Protobuf, XML or YAML; and even the large set of data format modules to support data types of widely used data types such as Guava, Joda, PCollections and many, many more…
If you are really only interested in serializing your objects to a file and then deserializing them later, then you might check out YAML instead of XML. YAML is much easier to work with than XML and the output files are very human-readable (which may or may not be a requirement). Check out yaml.org for more information. I've used JYAML successfully on a recent project.