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 need to get all the customer names. I need help on the looping part. This works for one customer
My Java code:
XMLInputFactory xif = XMLInputFactory.newFactory();
Reader reader = new StringReader(response.toString());
XMLStreamReader xsr = xif.createXMLStreamReader(reader);
while(xsr.hasNext()) {
if(xsr.isStartElement() && xsr.getLocalName().equals("customer")) {
break;
}
xsr.next();
}
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBElement<Customer> jb = unmarshaller.unmarshal(xsr,Customer.class);
Customer customer = jb.getValue();
System.out.println(customer.NAME);
Customer Class:
@XmlRootElement(name = "customer")
public class Customer {
public String NAME;
public String getNAME ()
{
return NAME;
}
}
Data Class:
@XmlRootElement(namespace = "data")
public class Data
{
@XmlElementWrapper(name = "data")
// XmlElement sets the name of the entities
@XmlElement(name = "customer")
{
private Customer[] customer;
public Customer[] getCustomer ()
{
return customer;
}
<data>
<customer>
<name>ABC</name>
<city>DEF</city>
</customer>
<customer>
<name>ABC</name>
<city>DEF</city>
</customer>
<customer>
<name>ABC</name>
<city>DEF</city>
</customer>
</data>
If you don't want to map a class to the outer most
data
element, below is how you could use StAX as per your original question.If you create Data class with proper JaxB annotations and with field that is a list of Customers, you will be able to unmarshall entire thing at once without iterating through xml string.
Here is a revision of you Java classes Data and Customer, plus some code to unmarshal:
Not sure why you use an XMLStreamReader, but you can change this if you like.