Can we create a class from a xml file? - java

Is it possible to create a class dynamically by reading an xml file ( in java preferably) ? if yes, please provide pointers on how to do it.
In the process of development, we have come up with a class that has 5 attributes, all these attributes correspond to an entry in the xml file, now if the user adds/modifies the xml entry the object corresponding to it must change automatically, one approach would be generate the source code, before compile time.Is there any other way ?
Is there any common pattern to model such changes in the system ?
Thanks,

If you have an XML Schema for your XML there are a number of kits for this. Start with JAX-B.

If you stored your attributes in a HashMap then you could simply parse the XML and then set the attributes accordingly.

Assuming you have a XML schema (xsd), you can feed that schema to JAXB's xjc command to generate Java classes. xjc is included with the Java 6 JDK.

The process usually works the other way around (ie. defining a class with those attributes, and serializing an instance of the class to XML)
If you really need that sort of flexibility, a scripting language would save you a lot of trouble.

I think JAX-B can provide functionality like that.

If you're looking for byte code generation, have a look at cglib, it is the one used in Hibernate.
But maybe some annotations can also fulfill your requirement, just like Google Guice's dependency injection.

Related

Java to XSD or XSD to Java

I know that, using JAXB, you can generate Java files from an XSD and that you can also generate the XSD from annotated POJOs. What are the advantages and disadvantages of each? Is one overall better than the other?
We basically want to serialize events to a log in XML format.
Ultimately it depends on where you want to focus:
If the XML Schema is the Most Important Thing
Then it is best to start from the XML schema and generate a JAXB model. There are details of an XML schema that a JAXB (JSR-222) implementation just can't generate:
A maxOccurs other than 0, 1, or unbounded
many facets on a simple type
model groups
If the Object Model is the Most Important Thing
If you will be using the Java model for more than just converting between objects and XML (i.e. using it with JPA for persistence) then I would recommend starting with Java objects. This will give you the greatest control.
It depends on your requirement and scenario with respect to the point of initiation.
Given your requirement, use generate Java files from an XSD as you want to define the output(XML) format first which should be supported by Java.,
Given that one of the main points of XML is to be a portable data-transfer format, usable regardless of platform or language, I would avoid generating XSD from any specific programming language, as a rule of thumb. This may not matter if you know you are only communicating between Java endpoints (but are you sure this will be true forever?).
It is better, all else being equal, to define the interface/schema in a programming-language neutral way.
There are lots of exceptions to this general principle, especially if you are integrating with existing or legacy code...
If you have the opportunity to design both pojo and schema, It's a matter of design - do you design for a "perfect" schema or for a "perfect" java class.
In some cases, you don't have the luxury of a choice, in system integration scenarios, you might be given a predefined XSD from another system that you need to adapt to, then XSD -> Class will be the only way.

Java - Generating XML for a legacy system

I'm working on an existing system that's generating XML for a legacy system using a simple template language. This is obviously not ideal because it's difficult to see the structure of the generated XML, it suffers from escaping problems and it's easy to generate invalid XML.
For any sane XML formats I'd just Xstream or another Java XML serializing library, but this legacy system has a lot of strange rules like "this node should be excluded if the value is less then ten" and "the formatting of the date in node x depends on the value of node y". There are other strange rules as well, but this should be enough to get the idea.
As I've said, the template approach is far from idea, but it's pragmatic and works (with some effort). Is there a better way to approach generating XML for legacy systems with this amount of formatting rules? XSL has crossed my mind, but implementing any amount of logic in XSL is frankly not very tempting.
Basically you need some custom logic during serialization. I am guessing that the in-memory object structure is not directly mirrored in the XML structure? Alternatives:
Use StAX and distribute read and write methods within the objects.
Use JAXB and insert custom serialization.
Don't even think of expressing your custom logic in anything other than java, i.e. some "super" framework.
I am not sure, if this is what you are looking for, but maybe try XML Binding like JAXB...
In other words: you could generate a class library from your xsd-Schema and then build your object graph in java code, then serialize it in one call to xml.
You could use simple xml and some converters I think:
http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php

How to create a handler for parsing a xml using SAX?

I'm using xerces SAX to parse this XML:
<product id="123">
<sku>abc123</sku>
<location>
<warehouse>1</warehouse/>
<level>3</level>
</location>
<details>
<weight unit="kg">150</weight/>
<mfg>honda</mfg>
</details>
</product>
So I created my own class named ProductSAXHandler.java:
public class ProductSAXHandler extends DefaultHandler {
}
Now from my spring mvc controller I plan on pass my XML file as a string, and I want a Product object returned.
So inside my ProductSAXHandler I will create my startElement, endElement methods.
So should I just create a method that takes the xml as a string, then instantiates this ProductSAXhandler and then call parse?
This is my first time dealing with xml/sax so I'm a little unclear how to design this class.
This doesn't directly answer your question, but I'm gonna read a bit between the lines and focus on your actual intention...
Since you want an instance of some Product class that encapsulates the data from the XML, probably in a structured way by preference, you'd do much better to use JAXB for this task. Unless you have really specific requirements regarding the customization of binding XML input to objects, this will turn out a lot simpler than using SAX.
What you'll need to do is:
Get a W3C XML Schema for your XML. If you don't have one and can't obtain one, then there are tools out there that can generate a schema based on input XML. Trang makes this very easy.
Generate Java classes from the schema. For this you can use XJC (the XML-to-Java Compiler) available with Sun's JDK. If you're using build tools like Ant or Maven, there's plugins available. This can automate the process to make it part of a full build.
Use the JAXB API with your generated classes to easily turn XML documents into objects and vice-versa.
Although JAXB will take some time to learn (especially if the desired XML-Java mapping isn't 1-to-1), I think you'll end up saving time in the long run.
Sorry if you really do need SAX and this answer is not applicable, but I figured I'd rather let you know your options before using a somewhat archaic XML processing model. Note that DOM and StAX might also be of interest to you.

Convert xml to java

How can I convert xml to java so that it could read the xml document and put it in to a database?
Your question is rather obscure and general. There are a number of options for converting XML to Java objects:
JAXB
XStream
XMLBeans
This article could be useful.
But anyway you will have to read much before getting something more complex to work.
This is all in case you need to map your xml to java objects. If you just need to parse the XML:
dom4j
xerces
JAXP
Check this: http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
That's how you read xml file. Then you just crate SQL query to insert it into database (JDBC?)
It's not clear at all, but if you are talking about parsing a XML file to do whatever you want with it in Java (also storing it in a database) you have to already ready choices:
using a DOM parser
using a SAX parser
both are covered here just to give you an example, but check documentation for better explaination.
Apparently JAXB can do marshalling/unmarshalling. I've not used it, but it seems to do what you want. From there, you can use an ORM of some type to put your objects in a database, or you can handcraft SQL.
It sounds like you are looking for something like JAXB or Castor. They both let you convert from a Java object -> XML and XML -> Java object.
Check Hyperjaxb3. It is a JAXB plugin which makes schema-derived classes to JPA entities. Thus you can easily do XML <-(JAXB)-> Java <-(JPA)-> RDB.
For this I recommend EclipseLink. EclipseLink offers both JAXB (object-to-XML) and JPA (object-to-Database) support.
The EclipseLink JAXB (MOXy) implementation offers all the extensions you need for mapping JPA entities to XML, for more information see:
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JPA
Use this https://json2csharp.com/xml-to-java in case you're looking for an online tool, you can then deserialize your object and fill it in the database

Denormalize an XML schema programmatically

I need to take any given valid XML schema (XSD) and denormalize it to a simple form containing no refs, no includes, etc. All simple type definitions should be inline, such that when looking at any given element, all declarations are visible without performing another lookup.
I've found some tools that have this built-in, but I need to do it "on the fly." Platform of choice is Java, but I'd be willing to port the code from another language if necessary. I just really don't want to reinvent the wheel here. Searching for OSS libraries from Apache/etc have yielded nothing. The closest I've found is XSOM which supports traversing a schema as an object model, but you still have to handle every possible form that a schema could take to represent a given structure.
The output doesn't have to be actual XML, as it will actually be used in a object model in its final form.
You might find XSD4J helpful:
http://dynvocation.selfip.net/xsd4j/
The EMF XSD model may be helpful:
http://www.eclipse.org/modeling/mdt/?project=xsd
Another useful API for XML Schema is XSOM.
XSOM is used by XJC, JAXB schema compiler under the hub so is probably guaranteed to be kept alive.

Categories