Java object for XML Schema

If you have a Java object and an XML Schema (XSD), then what is the best way to take this object and convert it to an XML file according to the scheme. The object and the schema do not know about each other (in that the Java classes were not created from the schema).

For example, the class may have an integer field "totalCountValue" that corresponds to an element called "countTotal" in the xsd file. Is there a way to create a mapping that says "if the object contains int totalCountValue, create an element called" CountTotal "and put it in XML." Likewise, there may be a field in the object that should be ignored, or a list in the object that should match multiple XML elements.

I looked at XStream but did not see a (obvious) way to do this. Are there other XML libraries that can simplify this task?

+3
source share
7 answers

I believe this can be achieved through JAXB using its annotations. It was usually easier for me to create objects from JAXB (as defined in your schema) using XJC than to map an existing Java object according to my schema. YMMV.

+6
source

I am making an Object to serialize XML using XStream. What do you not see “obvious” with this serializer? Once you get it hanging is very simple.

In the above example, you might have something like this:

...
XStream xstream = new XStream(new DomDriver());

xstream.alias("myclass", MyClass.class);
xstream.aliasField("countTotal", MyClass.class, "totalCountValue");

String xml = xstream.toXML(this);
...

for this class of samples:

class MyClass {
     private int totalCountValue;

     public MyClass() {
     }
} 

, - "", , , . ...

- XStream

+4

java JiBx . ( XML), , , XML- java-. , . .

+2

, , . , , , StAX Woodstox.

, , , , Woodstox . ( , XStream 30-40%). .

, XML ( ) , , .

+2

Apache Commons Betwixt. bean XML, , .

+1
+1

I would say JAXB or Castor. I found Castor easier to use and more reliable, but JAXB is standard

0
source

Source: https://habr.com/ru/post/1699128/


All Articles