I am new to Java programming and I am doing Unmarshalling the following XML string. My task is get the names of the customers in this string. I have done it for one customer. I
Here is a revision of you Java classes Data and Customer, plus some code to unmarshal:
@XmlRootElement
public class Response {
@XmlElement
private Data data;
public Data getData(){ return data; }
public void setData( Data value ){ data = value; }
}
public class Data { // omitted namespace="data" as it isn't in the XML
@XmlElement(name = "customer")
private List customer; // List is much better than array
public List getCustomer (){
if( customer == null ){
customer = new ArrayList<>();
}
return customer;
}
}
@XmlType(name = "Customer")
public class Customer {
private String name; // stick to Java conventions: lower case
public String getName (){
return name;
}
public void setName( String value ){
name = value;
}
}
JAXBContext jc = JAXBContext.newInstance( Response.class );
Unmarshaller m = jc.createUnmarshaller();
Data data = null;
try{
// File source = new File( XMLIN );
StringReader source = new StringReader( stringWithXml ); // XML on a String
data = (Data)m.unmarshal( source );
for( Customer cust: data.getCustomer() ){
System.out.println( cust.getName() );
}
} catch( Exception e ){
System.out.println( "EXCEPTION: " + e.getMessage() );
e.printStackTrace();
}
Not sure why you use an XMLStreamReader, but you can change this if you like.