xstream: map object to xml excluding one field - java

I have a class to map into XML using xstream.
Class is having 5 fields. Out of these five fields I want one field that should not be mapped to xml and only four fields should be mapped into XML.
E.g
public class Person {
private String firstname;
private String lastname;
private String phone;
// ... constructors and methods
}
When this class is mapped I want XML like this i.e. no phone number
<person>
<firstname>Joe</firstname>
<lastname>Walnes</lastname>
</person>

xstream.omitField(Person.class, "phone");
or in annotation

With classic Java code:
XStreamMarshaller marshaller = ... //Get your XStreamMarshaller
marshaller.getXStream().omitField(Person.class, "phone");
With annotation:
#XStreamOmitField
private String phone;
For the second case, you must call marshaller.getXStream().autodetectAnnotations(true); or marshaller.getXStream().processAnnotations(Person.class); to be sure that annotations are used.

Related

XML Mapping to Java Object

I have a Xml Like this
<entry>
<comboBox>
<name>xxx</name>
<details>sdfd</details>
</comboBox>
</entry>
In the other entry I have XML like this
<entry>
<numberField>
<name>xxx</name>
<details>sdfd</details>
</numberField>
</entry>
I want to map both comboBox and numberField to the same class in Java called Field
How do I annotate Java Fields in Entry Class?
In your Entry class you need to annotate the Java field with
#XmlElements
and list the individual element names there. Like this:
#XmlAccessorType(XmlAccessType.FIELD)
public class Entry {
#XmlElements({
#XmlElement(name = "comboBox", type = Field.class),
#XmlElement(name = "numberField", type = Field.class)
})
private Field field;
}
I have added type = Field.class in the annotation above only for clarity.
In your case you can omit it. Then JAXB will pick up Field from the property type decaration , which has the same desired effect.
The Field class can be straight-forward like this:
#XmlAccessorType(XmlAccessType.FIELD)
public class Field {
#XmlElement
private String name;
#XmlElement
private String details;
}
I think you should make two sub classes of an object which has the common annoted fields.
Each sub class just has to define jaxb #XmlRootElement (number field or combobox)

Unmarshalling in Jaxb with different tag with same name

I need to unmarshall a xml file which can return tag in following two ways.
<return_msg>Invalid Bank Code.</return_msg>
Second one
<return_msg>
<status_desc>Ok</status_desc>
<status_code>0</status_code>
</return_msg>
How can I create JAXB model class for this tag
Haven't tried, but you should be able to use this :
#XmlRootElement(name="return_msg")
#XmlAccessorType(XmlAccessType.FIELD)
public class ReturnMsg{
#XmlElement
private String status_desc;
#XmlElement
private String status_code;
#XmlMixed
private List<String> mixedContent;
//Getters and Setters
}
The mixed content should contains your "Invalid Bank Code." message if it's there.

Export specific fields on XML extraction in Java

I am using #XmlRootElement annotation to get XML data from the database.
Right now, if I put #XmlTransient to getters, the fields are ignored.
For example:
public class Student {
private Integer studentId;
private String studentName;
#XmlTransient // Do not get student id
public Integer getStudentId() {
return this.studentId;
}
public String getStudentName() {
return this.studentName;
}
...// Setter goes here
Then, student ids are not appear in the XML file.
However, can I do this in the opposite way? I want to specify fields that I want to have in the XML file - there are too many fields in the Student class.
My server(Spring Framework 3.2.3) also uses the Jackson library, so I wonder I could use it if that is possible.
You could annotate your class with:
#XmlAccessorType(XmlAccessType.NONE)
Now you have to explicitly map properties in order to be serialized. See the Javadoc: http://docs.oracle.com/javaee/7/api/javax/xml/bind/annotation/XmlAccessType.html

Map XML(of same tag name) to Java Object

I got a requirement that I have to map my xml to java object without parsing it, but the problem is like that in xml tag names would be same, for example,
<response>
<employee>
<name>Sharique</name>
<name>24</name>
<name>India</name>
</employee>
</response>
and class would be like this
public class Employee{
private String empName;
private int age;
private String country;
//getters and setters
}
Please help!!
If it can be done using spring than that would be very nice
If you leverage EclipseLink MOXy as your JAXB (JSR-222) provider then you can use our #XmlPath extension for this use case.
#XmlAccessorType(XmlAccessType.FIELD)
public class Employee{
#XmlPath("name[1]/text()")
private String
#XmlPath("name[2]/text()")
private int age;
#XmlPath("name[3]/text()")
private String country;
//getters and setters
}
For More Information
I have written more about the #XmlPath extension on my blog:
http://blog.bdoughan.com/2010/07/xpath-based-mapping.html
Not required, As per javax.xml.bind.annotation you can do like below,
#XmlElement(name="name")
private String empName;
So now the empName in your java class will be mapped to name attribute in your XML.
and your XML should not have 'name' as name for all attributes. it cannot differentiate, so you need to use different tags in your XML for other elements like age and so on ans map accordingly as i stated above in your POJO.
You really got some weird XML there. I thing data binding will not help in this case, but you can do it with data projection. (Disclosure: I'm affilited with that project)
public class ParseResponse {
public interface Employee {
#XBRead("./name[1]")
String getName();
#XBRead("./name[2]")
int getAge();
#XBRead("./name[3]")
String getCountry();
}
public static void main(String[] args) {
List<Employee> employees = new XBProjector().io().url("res://response.xml").evalXPath("//employee").asListOf(Employee.class);
for (Employee employee:employees) {
System.out.println(employee.getName());
System.out.println(employee.getAge());
System.out.println(employee.getCountry());
}
}
}
this program prints out
Sharique
24
India
if you fix the XML closing tags.

java Map to XML through XSD

First. Sorry for bad english.
I want to make some "common" transformation of Map to XML according to given XSD in that way:
key of the Map will be equal to tag name in XML
tag names in XML will not be duplicated in different nodes (levels)
value in Map can contain for example List of Map that represent repeatable tags in the node
created xml have to accord an xsd.
etc.
So I am looking for a competent way to realize that.
Is there anybody who worked with similar tasks and can help me?
Any advise will appreciated. Thanks in advance!
P.S. Example.
Map:
"fname" : "Asdf"
"lname" : "Fdsa"
"cars" : "car" {"car1", "car2", "car3"}
XML:
<fname>Asdf</fname>
<lname>Fdsa</lname>
<cars>
<car>car1</car>
<car>car2</car>
<car>car3</car>
</cars>
First, you need one single root element. This is the requirement of XML syntax.
Now you can use JAXB. Define you class Data:
#XmlType
public class Data {
private String fname;
private String lname;
private Collection<String> cars;
// getters
public String getFname() {
return fname;
}
public String getLname() {
return lname;
}
#XmlElementWrapper(name = "cars")
#XmlElement(name = "car")
public String getCars() {
return cars;
}
// setters.....
}
Now your can create instance of this class instance, call all setters to fill the data and then call:
JAXBContext ctx = JAXBContext.newInstance("com.yourpackage");
Marshaller m = ctx.createMarshaller();
m.marshal(data, System.out);
And you will see your data serialized as XML on STDOUT.
To parse XML back say:
JAXBContext ctx = JAXBContext.newInstance("com.panpwr.api.model.deployment");
Unmarshaller unmarshaller = ctx.createUnmarshaller();
Data data = (Data)unmarshaller.unmarshal(in); // in is the input stream for XML
// now your instance of data is populated from XML

Categories

Resources