How to convert xml to java - java

i am trying to convert from xml file to java, i have no experiance with that. So can some one please help me with it.
this is my book class below.
import java.util.*;
import javax.xml.bind.annotation.*;
#XmlRootElement(name= "book")
public class book {
private String ID;
private String title;
private String author;
private String genre;
private String price;
private String publicationDate;
private String discription;
public book(String a, String b, String c, String d, String e, String f, String g ){
ID = a;
title = b;
author = c;
genre = d;
price = e;
publicationDate = f;
discription = g;
}
#XmlElement
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
#XmlElement
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#XmlElement
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
#XmlElement
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
#XmlElement
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
#XmlElement
public String getPublicationDate() {
return publicationDate;
}
public void setPublicationDate(String publicationDate) {
this.publicationDate = publicationDate;
}
#XmlElement
public String getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
}
now i want to convert the xml file into java objects the xml file i will attach bellow.`
<?xml version="1.0"?>
<catalog>
<book id="1">
<author>Isaac Asimov</author>
<title>Foundation</title>
<genre>Science Ficition</genre>
<price>164</price>
<publish_date>1951-08-21</publish_date>
<description>Excellent.</description>
</book>
<book id="2">
<author>Isaac Asimov</author>
<title>Foundation and Empire</title>
<genre>Science Fiction</genre>
<price>79</price>
<publish_date>1952-10-12</publish_date>
<description>Good.</description>
</book>
</catalog>
so far i tried to convert and read the xml file by creating the method bellow in my man class
enter code here
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void unma() throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(book.class);
Unmarshaller um = jc.createUnmarshaller();
book b = (book) um.unmarshal(new File("src/Dv600/books.xml"));
System.out.println("information");
System.out.println("id" + b.getID());
System.out.println("Author" + b.getAuthor());
System.out.println("description" + b.getDiscription());
}
public static void main(String[] args) throws JAXBException {
unma();
}
}

There are couple of issues with your code.
#XMLAttribute is the correct annotation for id as as per your xml ID
is an attribute of book not an element as author or description.
#XMLElement should be on the setter method not on the getter method
Not sure why you have a constructor in book.java, remove that as well.
What is Catalog, there is no need for that. I have attached the working code please let me know if you have any questions.
************** TEST.java************
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class Test {
public static void unma() throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(Books.class);
Unmarshaller um = jc.createUnmarshaller();
Books b = (Books) um.unmarshal(new File("c:/tester/books.xml"));
for (int i =0;i<b.getBooks().size();i++) {
Book bb = b.getBooks().get(i);
System.out.println(bb.getAuthor());
System.out.println(bb.getTitle());
System.out.println(bb.getDescription());
System.out.println(bb.getGenre());
System.out.println(bb.getPrice());
System.out.println(bb.getDate());
}
}
public static void main(String[] args) throws JAXBException {
unma();
}
}
**********Books.java**********
import java.util.*;
import javax.xml.bind.annotation.*;
#XmlRootElement(name="Books")
public class Books {
List<Book> books;
public List<Book> getBooks() {
return books;
}
#XmlElement( name = "Book" )
public void setBooks( List<Book> books )
{
this.books = books;
}
}
*************Book.java********
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlType( propOrder = { "author", "description","title", "genre","price", "date"} )
#XmlRootElement( name = "Book" )
public class Book
{
String author;
String description;
String title;
String genre;
String price;
String date;
public String getAuthor() {
return author;
}
#XmlElement( name = "author" )
public void setAuthor( String author )
{
this.author = author;
}
public String getDescription() {
return description;
}
#XmlElement( name = "description" )
public void setDescription( String description )
{
this.description = description;
}
public String getTitle() {
return title;
}
#XmlElement( name = "title" )
public void setTitle( String title )
{
this.title = title;
}
public String getGenre() {
return genre;
}
#XmlElement( name = "genre" )
public void setGenre( String genre )
{
this.genre = genre;
}
public String getPrice() {
return price;
}
#XmlElement( name = "price" )
public void setPrice( String price )
{
this.price = price;
}
public String getDate() {
return date;
}
#XmlElement( name = "date" )
public void setDate( String date )
{
this.date = date;
}
}
**xml for book****
<?xml version="1.0"?>
<Books>
<Book id="1">
<author>Isaac Asimov</author>
<title>Foundation</title>
<genre>Science Ficition</genre>
<price>164</price>
<date>1951-08-21</date>
<description>Excellent.</description>
</Book>
<Book id="2">
<author>Isaac Asimov</author>
<title>Foundation and Empire</title>
<genre>Science Fiction</genre>
<price>79</price>
<date>1952-10-12</date>
<description>Good.</description>
</Book>
</Books>

Related

XML to java object using jaxb Unmarshalling namespace

I have below employee.xml which I am trying to convert to Java Object using JAXB. I am getting null value here, please guide me what I am missing here or doing wrong.
I am not familiar with JAXB and namespace <employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schema.cs.csg.com/cs/ib/cpm"> I thing I am missing some annotation or not using it properly.
Output:
Employee [id=null, firstName=null, lastName=null, department=null]
employee.xml
<?xml version="1.0"?>
<employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlnx="http://schema.cs.csg.com/cs/ib/cpm">
<department>
<id>101</id>
<name>IT</name>
</department>
<firstName>Rakesh</firstName>
<id>1</id>
<lastName>Yadav</lastName>
</employee>
Employee.java
package com.cs.xmltojava
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "employee", namespace="http://schema.cs.csg.com/cs/ib/cpm")
#XmlAccessorType(XmlAccessType.PROPERTY)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String firstName;
private String lastName;
private Department department;
public Employee() {
super();
}
public Employee(int id, String fName, String lName, Department department) {
super();
this.id = id;
this.firstName = fName;
this.lastName = lName;
this.department = department;
}
//Setters and Getters
public Integer getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
#Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", department="+ department + "]";
}
}
Department.java
package com.cs.xmltojava
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "department", namespace="http://schema.cs.csg.com/cs/ib/cpm")
#XmlAccessorType(XmlAccessType.PROPERTY)
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
Integer id;
String name;
public Department() {
super();
}
public Department(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
//Setters and Getters
public Integer getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Department [id=" + id + ", name=" + name + "]";
}
}
EmployeeMain.java
package com.cs.xmltojava
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class EmployeeMain {
public static void main(String[] args) throws Exception {
File xmlFile = new File("employee.xml");
JAXBContext jaxbContext;
try
{
jaxbContext = JAXBContext.newInstance(Employee.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile);
System.out.println(employee);
}
catch (JAXBException e)
{
e.printStackTrace();
}
}
}
create package-info.java in your package and remove
namespace="http://schema.cs.csg.com/cs/ib/cpm" from #XmlRootElement.
package-info.java
#XmlSchema(
namespace="http://schema.cs.csg.com/cs/ib/cpm",
elementFormDefault=XmlNsForm.QUALIFIED
)
package com.cs.xmlparser;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

Null values for XML attribute unmarshaling

This is my xml file and it is returning null values for type and currency when unmarshalling and rest all values are getting printed. I have used unmarshalling here and all Parent and Child POOJ are specified and finally my Main method calls unmarshall function
1) Vehicle.xml
<?xml version="1.0" encoding="UTF-8"?>
<Vehicle>
<car>
<manufacturer>Maruti</manufacturer>
<cost currency="INR">675000</cost>
<name type="sedan">Ciaz</name>
<fuelType>Petrol</fuelType>
<driverType>Manual</driverType>
</car>
<car>
<manufacturer>Maruti</manufacturer>
<cost currency="INR">575000</cost>
<name type="sedan">Dezire</name>
<fuelType>Petrol</fuelType>
<driverType>Manual</driverType>
</car>
</Vehicle>
Respective file are as
2) Vehicle.java
package jaxb;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "Vehicle")
public class Vehicle {
#XmlElement
private List<Car> car;
public List<Car> getCar() {
return car;
}
#Override
public String toString() {
return "Vehicle[ Car=" + car + "]";
}
}
3) Child for POJO Car.java
package jaxb;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="Car")
public class Car {
private String manufacturer;
private String name;
private String driverType;
private String fuelType;
private String currency;
#XmlAttribute
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
#XmlAttribute
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
private String type;
private int cost;
#XmlElement
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
#XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement
public String getDriverType() {
return driverType;
}
public void setDriverType(String driverType) {
this.driverType = driverType;
}
#XmlElement
public String getFuelType() {
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
#XmlElement
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
#Override
public String toString() {
return "Car [name=" + name + ", fuelType=" + fuelType + ", cost=" + cost+",driverType="+driverType +",currency="+currency+ " , type="+type +"]";
}
}
4) Fie for unmarshalling
package jaxb;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class VehicleJxb {
public void unmarhalling() {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Vehicle.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Vehicle vehicle = (Vehicle) jaxbUnmarshaller.unmarshal(new File("src\\main\\java\\Data\\Vehicle.xml"));
System.out.println(vehicle);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
5) Final Output
Vehicle[ Car=[Car [name=Ciaz, fuelType=Petrol, cost=675000,driverType=Manual,currency=null , type=null], Car [name=Dezire, fuelType=Petrol, cost=575000,driverType=Manual,currency=null , type=null]]]
With JAXB you can map attributes only on the same level. To map attributes on embedded elements you should use separate classes for these elements.
Here is how you can map attributes (publci attributes used for simplicity):
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
#XmlRootElement(name = "Car")
public class Car {
public static class Cost {
#XmlValue
public String value;
#XmlAttribute
public String currency;
#Override
public String toString() {
return "Cost[value=" + value + ", currency=" + currency + "]";
}
}
public static class Name {
#XmlValue
public String value;
#XmlAttribute
public String type;
#Override
public String toString() {
return "Name[value=" + value + ", type=" + type + "]";
}
}
private String manufacturer;
private Name name;
private String driverType;
private String fuelType;
#XmlAttribute
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
private String type;
private Cost cost;
#XmlElement
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
#XmlElement
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
#XmlElement
public String getDriverType() {
return driverType;
}
public void setDriverType(String driverType) {
this.driverType = driverType;
}
#XmlElement
public String getFuelType() {
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
#XmlElement
public Cost getCost() {
return cost;
}
public void setCost(Cost cost) {
this.cost = cost;
}
#Override
public String toString() {
return "Car [name=" + name + ", fuelType=" + fuelType + ", cost=" + cost + ",driverType=" + driverType + "]";
}
}
One common approach would be to add an extra class to handle the attribute + value. If you don't want the extra indirection when using Car. You can add a shortcut getter to it.
public class Car {
// .....
private Money cost;
public Money getCost() {
return cost;
}
public void setCost(Money cost) {
this.cost = cost;
}
/* Optional shortcut getter */
public String getCurrency(){
if(getCost()==null){
return null;
}
return getCost().getCurrency();
}
}
public static class Money {
private String currency;
private int amount;
#XmlAttribute
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
#XmlValue
public int getAmount() {
return amount;
}
public void setAmount(int cost) {
this.amount = cost;
}
}
try this:
#XmlAttribute(name = "cost currency")
public String getCurrency() {
return currency;
}
#XmlAttribute(name = "name type")
public String getType() {
return type;
}

How to get a value between tags with XML format using jaxb

I have a xml format like below:
<list>12
<item name="a">
<child parent="b" age="1">David Beckham</child>
</item>
</list>
The question is how could i extract 12 using JAXB? Which annotation supports it? Thank a lot.
Following is the working example.
import java.io.StringReader;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.transform.stream.StreamSource;
public class TestJAXBMixed {
public static void main(String[] args) throws Exception {
final String str =
"<list>12<item name=\"a\"><child parent=\"b\" age=\"1\">David Beckham</child></item></list>";
final JAXBContext jaxbContext = JAXBContext.newInstance(Child.class, Item.class, ListElement.class);
final JAXBElement<ListElement> obj = jaxbContext.createUnmarshaller().unmarshal(new StreamSource(new StringReader(str)), ListElement.class);
// The following is an array of objects representing the <list> content in order,
// i.e. it is a sequence of a String (12) and an Object (Item)
final List<Object> content = obj.getValue().getContent();
System.out.println(content);
}
}
#XmlRootElement(name="child")
class Child {
private String parent;
private String age;
private String text;
public String getParent() {
return parent;
}
#XmlAttribute(name="parent")
public void setParent(String parent) {
this.parent = parent;
}
public String getAge() {
return age;
}
#XmlAttribute(name="age")
public void setAge(String age) {
this.age = age;
}
public String getText() {
return text;
}
#XmlValue
public void setText(String text) {
this.text = text;
}
}
#XmlRootElement(name="item")
class Item {
private String name;
private Child child;
public String getName() {
return name;
}
#XmlAttribute(name="name")
public void setName(String name) {
this.name = name;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
}
#XmlRootElement(name="list")
class ListElement {
private List<Object> content;
public List<Object> getContent() {
return content;
}
#XmlMixed
#XmlElementRefs({
#XmlElementRef(name="item", type=Item.class)
})
public void setContent(List<Object> content) {
this.content = content;
}
}
SimpleXml can do it:
final String data = ...
final SimpleXml simple = new SimpleXml();
final Element element = simple.fromXml(data);
System.out.println(element.text);
Will output:
12
From maven central:
<dependency>
<groupId>com.github.codemonstur</groupId>
<artifactId>simplexml</artifactId>
<version>1.4.0</version>
</dependency>

JAXB Reading XML document

I'm trying to read an XML document and decode it in to Java Beans. I have the reading part settled but I run in to an issue. I'm basically trying to decode all the child nodes of the XML document, root being "catalog". How do I do this using the XMLDecoder?
XMLDecoder:
private static Book jaxbXMLToObject() {
try {
JAXBContext context = JAXBContext.newInstance(Book.class);
Unmarshaller un = context.createUnmarshaller();
Book book = (Book) un.unmarshal(new File("PATH"));
return book;
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
I'm trying to read the following document
<?xml version="1.0"?>
<catalog>
<book id="1">
<author>Isaac Asimov</author>
<title>Foundation</title>
<genre>Science Ficition</genre>
<price>164</price>
<publish_date>1951-08-21</publish_date>
<description>Foundation is the first novel in Isaac Asimovs Foundation Trilogy (later expanded into The Foundation Series). Foundation is a cycle of five interrelated short stories, first published as a single book by Gnome Press in 1951. Collectively they tell the story of the Foundation, an institute to preserve the best of galactic civilization after the collapse of the Galactic Empire.</description>
</book>
</catalog>
And Parse it in to a Book Object
#XmlRootElement(name = "book")
#XmlType(propOrder = {"id", "price", "title", "author", "genre", "description"})
public class Book {
private int id;
private int price;
private String title;
private String author;
private String genre;
private String description;
private Date publish_date;
public Book() {
}
......
I get the error: jjavax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"catalog"). Expected elements are <{}book>
How do I only access the child nodes using JAXB?
UPDATE
Catalog Class:
#XmlRootElement(name = "catalog")
public class Catalog {
#XmlElement(name = "book")
List<Book> books;
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
Book class:
#XmlAccessorType(XmlAccessType.FIELD)
public class Book {
#XmlAttribute
int id;
private int price;
private String title;
private String author;
private String genre;
private String description;
private Date publish_date;
public Book() {
}
public Book(int id, int price, String title, String genre, String description, Date publicationDate) {
this.id = id;
this.price = price;
this.title = title;
this.genre = genre;
this.description = description;
this.publish_date = publicationDate;
}
public int getId() {
return id;
}
public int getPrice() {
return price;
}
public String getTitle() {
return title;
}
public String getGenre() {
return genre;
}
public String getDescription() {
return description;
}
public Date getPublicationDate() {
return publish_date;
}
public void setId(int id) {
this.id = id;
}
public void setPrice(int price) {
this.price = price;
}
public void setTitle(String title) {
this.title = title;
}
public void setGenre(String genre) {
this.genre = genre;
}
public void setDescription(String description) {
this.description = description;
}
public void setPublish_date(String publish_date) {
this.publish_date = new Date();
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getPublish_date() {
return publish_date;
}
public String toJSON() {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(this);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public String toString() {
return "Book{" +
"id=" + id +
", price=" + price +
", title='" + title + '\'' +
", genre='" + genre + '\'' +
", description='" + description + '\'' +
", publicationDate=" + publish_date +
'}';
}
}
DAO:
public class BooksDAO {
public BooksDAO() {
}
public List<Book> getBooks() {
Catalog catalog = jaxbXMLToObject();
return catalog.getBooks();
}
private static Catalog jaxbXMLToObject() {
try {
return JAXB.unmarshal(new File("PATH"), Catalog.class);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
As already pointed out by JB Nizet you definitely need an enclosing Catalog object. The following is the bare minimum to be able to unmarshal the provided XML document using JAXB and extract the book from it:
public class ReadXMLUsingJAXB {
static class Catalog {
#XmlElement(name = "book")
List<Book> books;
}
#XmlAccessorType(XmlAccessType.FIELD)
static class Book {
#XmlAttribute
int id;
String author;
String title;
String genre;
int price;
Date publish_date;
String description;
}
private static Book firstBookFromXML() {
Catalog catalog = JAXB.unmarshal(new File("PATH"), Catalog.class);
return catalog.books.get(0);
}
public static void main(String[] args) {
Book book = firstBookFromXML();
System.out.println(book.id + ", " + book.author + ", " + book.title
+ ", " + book.genre + ", " + book.price
+ ", " + book.publish_date + ", " + book.description);
}
}
Some things are worth mentioning here:
The #XmlAccessorType-Annotation is not necessary with Catalog as there is only one field which is annotated with #XmlElement.
When chosing FIELD as access type all fields are taken into account regardless of their visibility unless annotated with #XmlTransient.
The book ID is an attribute in the document, so it must be declared as such using #XmlAttribute.
#XmlElement on Catalog.books was necessary to reflect the name of the book-Elements. JAXB defaults to the field (or property) name which would be books instead and thus not match the elements.
As said before the demonstration code is the bare minimum and should be changed to fit your needs (i.e. field visibility, proper constructor, getters, equals, hashCode, toString etc.)

multi instance xml file ummarshalling to objects

I am using JAXB to covert xml to objects. After doing some tutorial, I can successfully convert a simple xml (which has single object and unique element tag) to object. Then I need to deal with more complicated xml which has multiple instances and one parent tag. I still use the similar structure. But I couldn't get the expected output of three country objects. what is wrong with my code? Please help.
IntelliJ IDE console output is:
Countries#5e20a82a
Process finished with exit code 0
xml file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Countries>
<Country>
<Country_Name>Spain</Country_Name>
<Country_Capital>Madrid</Country_Capital>
<Country_Continent>Europe</Country_Continent>
</Country>
<Country>
<Country_Name>USA</Country_Name>
<Country_Capital>Washington</Country_Capital>
<Country_Continent>America</Country_Continent>
</Country>
<Country>
<Country_Name>Japan</Country_Name>
<Country_Capital>Tokyo</Country_Capital>
<Country_Continent>Asia</Country_Continent>
</Country>
</Countries>
Countries.java
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlType( propOrder = { "name", "capital", "foundation", "continent" , "population"} )
#XmlRootElement( name = "Countries" )
public class Countries {
private int population;
private String name;
private String capital;
private int importance;
private String foundation;
private String continent;
#XmlElement(name = "Country_Population")
public void setPopulation(int population) {
this.population = population;
}
#XmlElement(name = "Country_Name")
public void setName(String name) {
this.name = name;
}
#XmlElement(name = "Country_Capital")
public void setCapital(String capital) {
this.capital = capital;
}
#XmlAttribute(name = "importance", required = true)
public void setImportance(int importance) {
this.importance = importance;
}
#XmlElement(name = "Country_foundation")
public void setFoundation(String foundation) {
this.foundation = foundation;
}
#XmlElement(name = "Country_Continent")
public void setContinent(String continent) {
this.continent = continent;
}
}
CountryReader.java
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
public class CountryReader {
public static void main(String[] args) throws JAXBException {
File file = new File("country.xml");
JAXBContext jaxbContext = JAXBContext.newInstance( Countries.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Countries countres = (Countries)jaxbUnmarshaller.unmarshal( file );
System.out.println( countres );
}
}
You should separate the mapping of the root element and the nested collection elements.
So you'd have something like this:
#XmlRootElement( name = "Countries" )
public class Countries {
private List<Country> countries;
#XmlElement(name = "Country")
public void setCountries(List<Country> countries) {
this.countries = countries;
}
}
 
#XmlType( propOrder = { "name", "capital", "foundation", "continent" , "population"} )
#XmlRootElement( name = "Country" )
public class Country {
private int population;
private String name;
private String capital;
private int importance;
private String foundation;
private String continent;
#XmlElement(name = "Country_Population")
public void setPopulation(int population) {
this.population = population;
}
#XmlElement(name = "Country_Name")
public void setName(String name) {
this.name = name;
}
#XmlElement(name = "Country_Capital")
public void setCapital(String capital) {
this.capital = capital;
}
#XmlAttribute(name = "importance", required = true)
public void setImportance(int importance) {
this.importance = importance;
}
#XmlElement(name = "Country_foundation")
public void setFoundation(String foundation) {
this.foundation = foundation;
}
#XmlElement(name = "Country_Continent")
public void setContinent(String continent) {
this.continent = continent;
}
}
For more information about dealing with collections in JAXB, see this blog post. #XmlElementWrapper would seem suitable for your task, but I don't think it can be used directly with root elements.

Categories

Resources