Lets say I have a DOM object (or a string containing xml). Is it in any way possible to serialize the xml in such a way that each attribute appears on a new line?
This is the output I want:
<parent>
<anElement
attrOne="1"
attrTwo="2"
attrThree="3"
/>
</parent>
Preferred if the solution a part of the standard java api, but I suspect such a feature is not available in there, or am I wrong?
I found a property for a serializer in the .NET Framework, called NewLineOnAttributes. What I am searching for is something equivalent, but in java.
The DecentXML parser can do this.
The XOM library has a Serializer class which you can override to output in whatever format you want.
I don't know of any XML API for Java that provides that specific ability. I've checked the source code for JDOM and XOM, and they all print attributes on the same line, and provide no specific hooks for overriding that.
Both XOM and JDOM do have specific classes for serializing XML (XMLOutputter and Serializer, respectively), and both classes have protected or public methods for handling the serialization of attributes, so you could, if you wanted to, subclass those classes and override the appropriate methods to control your attribute formatting as you want it.
As for the standard Java API, though, forget it, that stuff is pretty nasty.
Related
I am using Weblogic Integration framework. While transforming one XML format to another using .xq file, I want to apply some logic written in a custom Java Class.
For example, XML1 has tag: <UnitCode>XYZ</UnitCode>
Custom Java Class:
public class unitcodemapper{
public static String getMappedUnitCode(String unitCode){
if(unitCode=="XYZ")
return <<value from DB table>>
else
return unitCode;
}
}
XML2 will have a tag: <UnitCode>unitcodemapper.getMappedUnitCode(XML1/UnitCode)</UnitCode>
I cannot find any documentation or example to do this. Can someone please help in understanding how this can be done?
This is known as an "extension function". The documentation for your XQuery implementation should have a section telling you how to write such functions and plug them into the processor. (The details may differ from one XQuery processor to another, which is why I'm referring you to the manual.)
Whilst #keshlam mentions Extension Functions, which are indeed supported by many implementations each with their own API.
I think perhaps what you are looking for instead is Java Binding from XQuery. Many implementations also support this and tend to use the same approach. I do not know whether WebLogic supports this or not! If it does, the trick is to use java: at the start of your namespace URI declaration, you can then use the fully qualified Java class name of a static class, each static method you may then call directly from that namespace.
You can from two examples of implementations that offer the same Java Binding from XQuery functionality here:
http://exist-db.org/exist/apps/doc/xquery.xml#calling-java
http://docs.basex.org/wiki/Java_Bindings
These could serve as examples for you to try on WebLogic to see if it is supported in the same way. However, I strongly suggest you check their documentation as they may take a different approach.
After taking quite a long break from active coding I am just starting to get accustomed to Java again, so this might be considered a "newbie question". Any help is appreciated.
Consider the following scenario. I am parsing an XML document as DOM. I am using javax.xml.parsers.DocumentBuilder to obtain an org.w3c.dom.Document node and scan through its org.w3c.dom.Element nodes, and I am fine with that.
However, I would like to extend the functionality of my org.w3c.dom.Element objects. Say, I would like to have a convenient way to extract some information from the nodes by giving them some public FancyObject toFancyObject() method. Whats the right way of doing this?
Considering that org.w3c.dom.Element is an interface, inheritance seems to be no option. Composition, on the other hand, seems to be quite cumbersome in this case, since this would be like 5% new functionality and 95% delegation of the existing methods.
Also, I am aware that I could always write a static utility method to obtain my FancyObject, but I would like to avoid this solution.
You have a couple of options:
Use the user data field of the Node interface. You can attach arbitrary objects to i t and build something that resembles your static variant.
Use JDOM or DOM4J instead. These APIs are better suited for your requirements w.r.t. extending base implementation classes. For example, with JDOM you can define a custom NodeFactory that can create the customized Element implementations.
Use JAXB to unmarshal the XML into an object graph. In this case, you have almost complete freedom to implement custom behavior.
I want to create a class dynamically at run time by reading field names and its types from an xml file.For example my xml file looks like this:
<person>
<name type="String">abc</name>
<age type="Integer">30</age>
</person>
I also want to have getter and setters methods for each field.
Any examples or best approaches available for this?
Take a look at XStream, it is extremely easy to serialize to/from XML.
This is technically possible, but (unless someone can point out an existing solution) it would be a lot of work. (You can do a lot of clever things by generating source code and compiling it at runtime ... for example.)
But to be honest, this is probably not a useful thing to do. Once you've loaded your XML object as an instance of a brand new Java class, you'll have great difficulty using it. For a start, your existing statically compiled application will only be able to access the fields and methods of the new class reflectively.
IMO, you'd be better of loading the XML into generic Map objects or Properties objects. Or, just use a DOM created by an off-the-shelf XML parser.
Alternatively, get hold of a DTD, XSD, or some other kind of "schema" for the XML and generate Java classes from that. Then can write and statically compile your application to call those classes.
Java is not a dynamic language, so you cannot create classes dynamically, but the term 'create' is not well defined in your question.
If you mean instantiate and initialize, that can be done very easily through serialization with libraries like:
jaxb.dev.java.net/
www.castor.org/
jibx.sourceforge.net/
http://x-stream.github.io/
etc.
If you mean you want to actually create a class file within the JVM at runtime, you might want to look at more dynamic langauges capable of running in a JVM like Groovy, or JRuby, etc. Groovy has some pretty cool dynamic capabilities.
I was wondering if there was a way to parse XML using E4X, or something similar to E4X.
Does such a framework / library exist?
Thanks!
You can use JavaScript engine Rahino with Java which can handle E4X.
http://blogs.oracle.com/sundararajan/entry/desktop_scripting_applications_with_netbeans
http://www.ibm.com/developerworks/library/ws-ajax1/
Java cannot support dynamically defined members, as JavaScript can.
However, with design-time generation, you can get Java whose members reflect the XML. E.g., JAXB
E4X is a language extension, XML is treated like a primitive. E4X is not just for parsing XML, it's using XML as real types.
This can't be simulated or done with a Java 'framework', it would require a language extension for Java.
There is no parsing XML with E4X. It is a specification that makes XML a native data type. Among browsers, only Firefox supports it as of now.
Here's a list of all known implementations of the spec.
A framework can only mimic making XML access easier, but will not fundamentally change the way we use XML. For example, the SimpleXML extension in PHP simplifies things a lot, but under the hood it converts elements to objects using reflection.
So to have something like E4X, it has to be implemented in the language itself and there is no other non-ECMAScript based language that has this as of now.
I need to decide on which one to use. My case is pretty simple. I need to convert a simple POJO/Bean to XML, and then back. Nothing special.
One thing I am looking for is it should include the parent properties as well. Best would be if it can work on super type, which can be just a marker interface.
If anyone can compare these two with cons and pros, and which thing is missing in which one. I know that XStream supports JSON too, thats a plus. But Simple looked simpler in a glance, if we set JSON aside. Whats the future of Simple in terms of development and community? XStream is quite popular I believe, even the word, "XStream", hit many threads on SO.
Thanks.
Just from reading the documentation (I'm facing down the same problem you are, but haven't tried either way yet; take this with a grain of salt):
XSTREAM
Very, very easy to Google. Examples, forum posts, and blog posts about it are trivial to find.
Works out of the box. (May need more tweaking, of course, but it'll give you something immediately.)
Converting a variable to an attribute requires creating a separate converter class, and registering that with XStream. (It's not hard for simple values, but it is a little extra work.)
Doesn't handle versioning at all, unless you add in XMT (another library); if the XML generated by your class changes, it won't deserialize at all. (Once you add XMT, you can alter your classes however you like, and have XStream handle it fine, as long as you create an increasing line of incremental versioning functions.)
All adjustments require you to write code, either to implement your own (de)serialization functions, or calling XStream functions to alter the (de)serialization techniques used.
Trivial syntax note: you need to cast the output of the deserializer to your class.
SIMPLE
Home page is the only reliable source of information; it lists about a half-dozen external articles, and there's a mailing list, but you can't find it out in the wild Internet.
Requires annotating your code before it works.
It's easy to make a more compact XML file using attributes instead of XML nodes for every property.
Handles versioning by being non-strict in parsing whenever the class is right, but the version is different. (i.e., if you added two fields and removed one since the last version, it'll ignore the removed field and not throw an exception, but won't set the added fields.) Like XStream, it doesn't seem to have a way to migrate data from one version to the next, but unlike XStream, there's no external library to step in and handle it. Presumably, the way to handle this is with some external function (and maybe a "version" variable in your class?), so you do
Stuff myRestoredStuff = serializer.read(Stuff.class, file);
myRestoredStuff.sanityCheck();
Commonly-used (de)serializing adjustments are made by adding/editing annotations, but there's support for writing your own (de)serialization functions to override the standard methods if you need to do something woolly.
Trivial syntax note: you need to pass the restored object's class into the deserializer (but you don't need to cast the result).
Why not use JAXB instead?
100% schema coverage
Huge user base
Multiple implementations (in case you hit a bug in one)
Included in Java SE 6, compatible with JDK 1.5
Binding layer for JAX-WS (Web Services)
Binding layer for JAX-RS (Rest)
Compatible with JSON (when used with libraries such as Jettison)
Useful resources:
Comparison, JAXB & XStream
Comparison, JAXB & Simple
I'd recommend that you take a look at Simple
I would also suggest Simple, take a look at the tutorial, there and decide for yourself. The mailing list is very responsive and you will always get a prompt answer to any queries.
So far I have never use Simple framework yet.
Based on my experience with Xstream. It worked well on XML. However, for JSON, the result is not as precise as expected when I attempt to serialize a bean that contain a List of Hashtable.
Thought I share this here.
To get XStream to ignore missing fields (when you have removed a property):
XStream xstream = new XStream() {
#Override
protected MapperWrapper wrapMapper(MapperWrapper next) {
return new MapperWrapper(next) {
#Override
public boolean shouldSerializeMember(Class definedIn,
String fieldName) {
if (definedIn == Object.class) {
return false;
}
return super.shouldSerializeMember(definedIn, fieldName);
}
};
}
};
This can also be extended to handle versions and property renames.
Credit to Peter Voss: https://pvoss.wordpress.com/2009/01/08/xstream
One "simple" (pun intended) disadvantage of Simple and Jaxb is that they require annotating your objects before they can be serialized to XML. What happens the day you quickly want to serialize someone else's code with objects that are not annotated? If you can see that happening one day, XStream is a better fit. (Sometimes it really just boils down to simple requirements like this to drive your decisions).
Was taking a quick look at simple while reading stackoverflow; as an amendment to Paul Marshalls helpful post, I thought i'd mention that Simple does seem to support versioning through annotations-
http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#version
Simple is much slower then XStream(in serialization objects to xml)
http://pronicles.blogspot.com/2011/03/xstream-vs-simple.html