Xstream: JAVA to XML - java

I want to create an JAVA object, that could be converted into XML structure
<a id="[numeric value]">[string value]</a>
I read the tutorials on Xstream site and googled some time, but I can't find solutions.
For example, to convert the POJO to
<many_a>
<a id="[numeric value]">
<name>[string value]</name>
</a>
...
</many_a>
I will create POJOs
#XStreamAlias("many_a")
class AList{
#XStreamImplicit(itemFieldName = "a")
List<A> list;
}
class A{
#XStreamAsAttribute
#XStreamAlias("id")
long id;
#XStreamAlias("name")
String name;
}
So, the question is which POJO I should create to get the XML above?

You can use Map<Integer,String> to marshal your object , if you have all entries in your xml as you specified.
Please refer to this question to get an idea.

I found the solution how to solve this issue without writing your custom converter.
See this thread:
XStream: convert collection with attributes

Related

JAXB Without Defining Class or Annotations

I would like to use JAXB to read and write only a few parts of a very large XML. I would like to be able to do this without having to define a root object class for every element and attribute in the XML. The example below outlines what I need:
I have the XML
<A>
<B/>
<C/>
<D/>
</A>
I would like to use JAXB to get two functions
public String getC() {
...
return C
}
public void writeC(String C) {
... // replaces C value with the paramter C inside the XML
}
Without having to define a new class A with the annotations for B, C, and D.
How can I do this with JAXB? Is there a faster / more efficient way to achieve what I am trying to do than JAXB or a simple File Reader and Writer?
The purpose of this is to use a GUI to load and edit config settings that are stored in an XML file. Thank you.
I managed to solve this by using StAX instead. It offered complete flexibility for me to pick out which tags and which attrbitues I needed.
There is a project called EclipseLink MOXy that could solve this type of problem using JAXB. It allows you to map an existing java bean to or from xml and define exceptions from default JAXB using xml or json for the mapping description.

Is it possible with Dozer to map from Java Object to xml?

What i want is:
I have a java DTO object...simple getters setters (dates,string, int..so on) and i want to generate from the jva object to a xml string..so for example:
DTOclass{
int id;
String name;
//Getters-settters
}
and i want to create like:
<id>dto.getId()</id> <!--With dozer of course...just call a map method and somehow i create a string from that-->
<name>dto.getName()</name>
Thanks a lot!
It's not possible with Dozer. The very first line of the About page states it's meant for mapping Java Beans to each other (and nothing else).
Maybe you could get creative and find another library to use in conjunction with Dozer.

How to generate xml in Java?

Please, tell me, how to generate XML in Java?
I couldn't find any example using SAX framework.
Try Xembly, a small open source library that wraps native Java DOM with a "fluent" interface:
String xml = new Xembler(
new Directives()
.add("root")
.add("order")
.attr("id", "553")
.set("$140.00")
).xml();
Will generate:
<root>
<order id="553">$140.00</order>
</root>
See this, this, Generating XML using SAX and Java and this
SAX is a library to parse existing XML files with Java. It is not to create a new XML file out of Java. If you want to do this use a library like DOM4J to create a XML tree and then write it to a file.
use dom4j, here is quick start for dom4j
dom4j guide
You can also use libraries like JAXB or SimpleXML or XStream if you want to easily map/convert your java objects to XML.
Say we have a simple entity/pojo - Item.The properties of the pojo class can be made the XML's element or attribute with simple annotations.
#Entity #Root public class Item {
#Attribute
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Transient
#ManyToOne
private Order order;
#Element
private String product;
#Element
private double price;
#Element
private int quantity; }
To generate XML from this item, the code can be simply
Serializer serializer=new Persister();//SimpleXML serializer
Item itemToSerializeToXml=new Item(2456L, "Head First Java", 250.00,10);//Object to be serialized
StringWriter destinationXMLWriter=new StringWriter();//Destination of XML
serializer.write(itemToSerializeToXml,destinationXMLWriter);//Call to serialize the POJO to XML
System.out.println(destinationXMLWriter.toString());
I found a nice library for XML creation on GitHub at https://github.com/jmurty/java-xmlbuilder . Really good for simple documents at least (I didn't have an opportunity to employ it for anything bigger than around a dozen lines).
The good thing about this library is that each of its commands (i.e. create attribute, create element, etc.) has 3 levels of abbreviations. For example, to add the tag <foo> to the document you can use the following methods:
.e("foo") (single-letter form)
.elem("foo" (4 letter form)
.element("foo") (fully spelled-out form)
This allows creating XML using both longer and more abbreviated code, as appropriate, so it can be a good fit for a variety of coding styles.

JAXB - can class containment be flattened when marshalling to XML?

Say, I have two classes:
#XmlRootElement
class A {
#XmlElement
String propertyOfA;
#XmlElement
B b;
}
class B {
#XmlElement
String propertyOfB;
}
JAXB returns an XML formatted in the according way:
<a>
<propertyOfA>valueA</propertyOfA>
<b>
<propertyOfB>valueB</propertyOfB>
</b>
</a>
My question is how to flatten the hierarchy in the XML? So that I have:
<a>
<propertyOfA>valueA</propertyOfA>
<propertyOfB>valueB</propertyOfB>
</a>
Can this be done with annotations?
At the moment I am thinking to create a kind of wrapper class for A, that would have fields built the way I want to see them in the XML. Is there a better way?
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
You could use MOXy's #XmlPath extension to map this use case:
import java.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
#XmlRootElement
class A {
#XmlElement
String propertyOfA;
#XmlPath(".")
B b;
}
For More Information
http://blog.bdoughan.com/2010/07/xpath-based-mapping.html
http://blog.bdoughan.com/2010/09/xpath-based-mapping-geocode-example.html
http://blog.bdoughan.com/2011/03/map-to-element-based-on-attribute-value.html
http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
It's been a while for me, but let me give it a crack:
#XmlRootElement
class A {
#XmlElement
String propertyOfA;
#XmlElement(name="propertyOfB")
B b;
}
#XmlType(name="")
class B {
#XmlValue
String propertyOfB;
}
Edit: disclaimer- I havn't compiled or tried this. But I believe it's how you do it.
Take a look to that question and the solution proposed: Spring RESTful client: root tag exception
Very helpful to solve this kind of problem.
An alternative approach (with standard JAXB) would be using #XmlJavaTypeAdapter. This way you could adapt the object hierarchy with the drawback of having to write the code that translates the object hierarchy into the adapted new class.
In your example however it wouldn't work as you would have to adapt class A which is your root. If however the hierarchy was deeper and you needed to make the adaptation one level lower than the root, then there wouldn't be a problem. A suggestion that might be useful is to write the code in the adapted entity, making it like a delegate to the object hierarchy, rather than the adapter, which would then be very thin.

How to map an XML to Java objects by XPaths?

Given the XML example:
<fooRoot>
<bar>
<lol>LOLOLOLOL</lol>
</bar>
<noob>
<boon>
<thisIsIt></thisIsIt>
</boon>
</noob>
</fooRoot>
Which should be mapped to:
class MyFoo {
String lol;
String thisIsIt;
Object somethingUnrelated;
}
Constraints:
XML should not be transformed, it is provided as a parsed org.w3c.dom.Document object.
Class does not and will not map 1:1 to the XML.
I'm only interested to map specific paths of the XML to specific fields of the object.
My dream solution would look like:
#XmlMapped
class MyFoo {
#XmlElement("/fooRoot/bar/lol")
String lol;
#XmlElement("/noob/boon/thisIsIt")
String thisIsIt;
#XmlIgnore
Object somethingUnrelated;
}
Does anything likewise exists? What I've found either required a strict 1:1 mapping (e.g. JMX, JAXB) or manual iteration over all fields (e.g. SAX, Commons Digester.)
JiBX binding definitions come the nearest to what I'm lokking for. However, this tool is ment to marshall/unmarshall complete hierarchy of Java objects. I only would like to extract parts of an XML document into an existing Java bean at runtime.
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
You can do this with MOXy:
#XmlRootElement(name="fooRoot")
class MyFoo {
#XmlPath("bar/lol/text()")
String lol;
#XmlElement("noob/boon/thisIsIt/text()")
String thisIsIt;
#XmlTransient
Object somethingUnrelated;
}
For More Information
http://blog.bdoughan.com/2010/07/xpath-based-mapping.html
http://blog.bdoughan.com/2010/09/xpath-based-mapping-geocode-example.html
http://blog.bdoughan.com/2011/03/map-to-element-based-on-attribute-value.html
http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
Try XStream. It's super easy. Hope it helps! I don't have time now for a full example :)
One option could be write a custom annotation which will take the XPath expression as input and do the bindings.

Categories

Resources