Generate Javabean from XML input - java

I need to create a javabean from xml input.There wont be any irregularities in the xml input which I give.
I know stuffs like JAXB and Apache XMLbeans work.
But here I need to autogenerate the JAVAbeanclass without using its xsd.
In short when I give any xml inputs the outputs have to be the pojo classes generated.
Any inputs for this???

I think the best solution for that is develop your own DOM (if there is many items on the XML) or SAX (if there is a lot of items) parser.
DOM takes more memory so it is not recommended for XML with many nodes (and/or many attributes).

You can use tools like wsgen to generate class files from a service.
Here is a example,
http://www.mkyong.com/webservices/jax-ws/jax-ws-wsgen-tool-example/

Related

How can i dynamically unmarshal xml in java?

I have a very large xml to unmarshal. I don't want to create POJO classes for this because that would mean creating around 20 classes. Is there a way I can unmarshal this dynamically i.e. without creating POJO classes?
Edit: Here is the link to the article to unmarshal (https://www.ncbi.nlm.nih.gov/pubmed/31297574/?report=xml&format=text)
I want to read this data and store it somewhere in my database.
I am trying to do this with jaxb.
The term "unmarshal" is usually used to mean a process of parsing XML and generating custom POJO objects. If you want to use generic Java objects instead, then you want one of the XML generic tree models. Most people use DOM, which is the oldest and worst of the models but is the default because it comes bundled with the Java platform; my own recommendation would be either JDOM2 or XOM.
If you don't want to create custom classes then you don't want to be using JAXB.
You haven't said in detail what you want to achieve, but for many XML operations, using XSLT or XQuery is going to be much easier than using Java (because processing XML is what they were designed for).
You can check DSM library. It's designed to process complex XML and JSON documents while reading the document. You define mapping definition in yaml format so you don't need to create classes to unmarshal.
DOM API load all XML to memory so that you can't use DOM with large XML. But DSM uses stream parsing so you won't face with memory problems. Using DSM is easier then DOM

Use xpath instead of XSD object generation for accessing XML details?

There is an XML file hosted on a server that I want to parse. Normally I generate an XSD from the XML and then generate the java pojo's from this XSD. Using jackson I then parse the XML to a java object representation. Is it not more straightforward to just use xpath ? This means I do not need to generate a object hierarchy based on the XML and also I do not need to regenerate the object hierarchy if the XML changes. xpath seems much more concise and intuitive ?
Why should I use XSD , object generation instead of xpath ?
According to the XML Schema specification XSD is used for defining the structure, content and semantics of XML documents. This means that you can use XSD to validate your XML file.
Depending on your circumstances you might be able to do without generating the whole object tree if all you need is to get some values from the XML file. In this case XPath is the way to go. However, you still might want to have an XSD file in order to validate the XML file before parsing it. This way you make your software fail fast, when the structure of your XML file changes, which will suggest that you change your XPath expressions. But for this to work, you shouldn't use the XSD you generate from your XML file, instead you should have a separate pre-generated XSD file which complies with the XPath expressions.
I think both approaches are valid, depending on the circumstances.
At the end of the day, you want to extract the values from that remote xml file and do something with them.
First criteria to consider is the size of that file, and the number of data elements.
If it's just a few, then xpath extraction should be straightforward. However, if that xml file represent a sizable and/or complex data structure, then you probably want the de-serialization to a Java data structure that you can then utilize, and JAXB would be a good candidate.
JAXB is going to be easier/better if the remote server adheres or publishes an XML Schema. If it doesn't, and changes often and significantly, you're going to suffer either way, but particularly so with JAXB. There are ways to smooth things over by pre-processing that xml with XSLT to force it into a more reliable form, but that is going to be a partial solution most likely.

How to generate XSD from elements of XML

I have a XML input
<field>
<name>id</name>
<dataType>string</dataType>
<maxlength>42</maxlength>
<required>false</required>
</field>
I am looking for a library or a tool which will take an XML instance document and output a corresponding XSD schema.
I am looking for some java library with which I can generate a XSD for the above XML structure
If all you want is an XSD so that the XML you gave conforms to it, you'd be much better off by crafting it yourself rather than using a tool.
No one knows better than you the particularities of the schema, such as which valid values are there (for instance, is the <maxlength> element required? are true and false the only valid values for <required>?).
If you really want to use a tool (I'd only advice using it if you haven't designed the XML and really can't get the real XSD - or if you designed it, double check the generated XSD), you could try Trang. It can infer an XSD Schema from a number of example XML's.
You'll have to take into account that the XSD a tool can infer you might be incomplete or inaccurate if XML samples aren't representative enough.
java -jar trang.jar sampleXML.xml inferredXSD.xsd
You can find a usage example of Trang here.
You can try with online tool called XMLGrid: http://xmlgrid.net/xml2xsd.html
You could write an XSLT to do something like that. But the problem is, a single document alone is not enough information to generate a schema. Are any of those elements optional? Is there anything missing from that document, that might appear in other instances? How many of a particular element can there be? Do they have to be in that order? There are loads of things that can be expressed in a schema, that are not immediately obvious from one instance of a document that conforms to that schema.
For the people who really want to include it in their Java code to generate an XSD and understand the perils, check out Generate XSD from XML programatically in Java
Try xmlbeans it has some tools one of them is ins2xsd you can find specifics here:
http://xmlbeans.apache.org/docs/2.0.0/guide/tools.html
Good luck

Parsing a xml file using Java

I need to parse a xml file using JAVA and have to create a bean out of that xml file after parsing .
I need this while using Spring JMS in which producer is producing a xml file .First I need to read the xml file and take action according .
I read some thing about parsing and come with these option
xpath
DOM
Which ll be the best option to parse the xml file.
did you check JAXB
There's three ways of parsing an XML file, SAX, DOM and StAX.
DOM will parse the whole file and build up a tree in memory - great for small files but obviously if this is huge then you don't want the entire tree just sitting in memory! SAX is event based - it doesn't load anything into memory per-se but just fires off a series of events as it reads through the file. StAX is a median between the two, the application moves the cursor forward as it needs, grabbing the data as it goes (so no event firing or huge memory consumption.)
What one you use will really depend on your application - all have built in libraries since Java 6.
Looks like, you receive a serialized object via Java messaging. Have a look first, how the object is being serialized. Usually this is done with a library (jaxb, axis, ...) and you could use the very same library to create a deserializer.
You will need:
The xml schema (a xsd file)
The Java bean class (very helpful, it should exist)
Then, usually the library will create all helper classes and files and you don't have to care about parsing.
if you need to create an object, just extract the needed properties and go on...
I recommend using StaX, see this tutorial for more information.
Umh..there are several ways you can parse an xml document to into memory and work with it. You mentioned DOM. DOM actually holds uploads the whole document into memory and then allows you to move between different branches of the XML document.
On the other hand, you could use StAX. It works similar to DOM. The only difference is that, it streams the content of the XML document thus allowing better allocation of memory. On the other hand, it does not retain the information that has already been read.
Look at : http://download.oracle.com/javaee/5/tutorial/doc/bnbem.html It gives details about both parsing methods and example code. Hope that helps.

How to deserialize Java objects from XML?

I'm sure this might have been discussed at length or answered before, however I need a bit more information on the best approach for my situation...
Problem:
We have some large XML data (anywhere from 100k to 5MB) which we need to inflate into Java objects. The issue is that the data doesn't really doesn't map onto an object very well at all, so we need to only pull certain parts of the data out and create the objects. Given that, solutions such as JAXB or XStream really aren't appropriate.
So, we need to pull XML data out and get it into java objects as efficiently as possible.
Possible Solutions:
The way I see it, we have 3 possible solutions:
SAX parsing
DOM parsing
XSLT
We can load the XML into any JAXP implementation and pull the data out using one of the above methods.
Question(s)
I have a few questions/concerns:
How does XSLT work under the hood? Is it just a DOM parser? I ask because XSLT seems like a good way to go, but I don't really want to consider it if it won't give us better performance than DOM.
What are some popular libraries that provide DOM, XSLT, and SAX XML parsers?
In your experience, what are the reasons for picking DOM, SAX, or XSLT? Does the ease of use of DOM or XSLT totally dominate the performance improvements SAX offers?
Any benchmarks out there? The ones I've found are old (as in, 8 years old). So some recent benchmarks would be appreciated.
Are there any other solutions besides those outlined above that I could be missing?
Edit:
A few clarifications... You can use XSLT to directly inject values into a Java object... it is normally used to transform XML into some other XML, however I'm talking from the standpoint of calling a method from XSLT into java to inject the value.
I'm still not clear on how an XSLT processor works exactly... How is it feeding the XML into the XSLT code you write?
Use XSLT to transform the large XML files into a local domain model that is mapped to java objets with JAXB.
Start with the JDK 5+ built in XML libraries (unless you absolutely need XSLT 2.0, in which case use Saxon)
Don't focus on relative performance of SAX/DOM, focus on learning how to write XPath expressions and use XSLT, and then worry about performance later if and only if you find it to be a problem.
The Eclipse XML editors are decent, but if you can afford it, spring for Oxygen XML, which will let you do XPath evaluation in realtime.
We had a similar situation and I just threw together some XPath code that parsed the stuff I needed.
It was amazingly quick even on 100k+ XML files. We went as low tech as possible. We handle around 1000 files a day of that size and parsing time is very low. We have no memory issues, leaks etc.
We wrote a quick prototype in Groovy (if my memory is accurate) - proof of concept took me about 10 minutes
JAXB, the Java API for XML Binding might be what you want. You use it to inflate an XML document into a Java object graph made up of "Java content objects". These content objects are instances of classes generated by JAXB to match the XML document's schema
But if you already have a set of Java classes, or don't yet have a schema for the document, JAXB probably isn't the best way to go. I'd suggest doing a SAX parse and then building up your Java objects during the parse. Alternatively you could try a DOM parse and then walk the resulting Document tree to pull out the parts of interest (maybe with XPath) -- but 5MB of XML might turn into 50MB of DOM tree objects in Java.
DOM, SAX and XSLT are different animals.
DOM parsing loads the entire document into memory, which for 100K to 5MB (very small by today's standards) would work.
SAX is a stream parser which reads the XML and delivers events to your code for each tag.
XSLT is a system for transforming one XML tree into another. Even if you wrote a transform that converts the input to a more suitable format, you'd still have to write something using DOM or SAX to convert it into Java objects.
You can use the #XmlPath extension in EclipseLink JAXB (MOXy) to easily handle this use case. For a detailed example see:
http://bdoughan.blogspot.com/2010/09/xpath-based-mapping-geocode-example.html
Sample Code:
package blog.geocode;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.eclipse.persistence.oxm.annotations.XmlPath;
#XmlRootElement(name="kml")
#XmlType(propOrder={"country", "state", "city", "street", "postalCode"})
public class Address {
#XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:SubAdministrativeArea/ns:Locality/ns:Thoroughfare/ns:ThoroughfareName/text()")
private String street;
#XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:SubAdministrativeArea/ns:Locality/ns:LocalityName/text()")
private String city;
#XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:AdministrativeAreaName/text()")
private String state;
#XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:CountryNameCode/text()")
private String country;
#XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:SubAdministrativeArea/ns:Locality/ns:PostalCode/ns:PostalCodeNumber/text()")
private String postalCode;
}

Categories