JAXB Unmarshalling XML string - Looping through al

2020-04-30 02:57发布

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>

3条回答
够拽才男人
2楼-- · 2020-04-30 03:16

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.

import java.io.*;
import javax.xml.bind.*;
import javax.xml.stream.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        XMLInputFactory xif = XMLInputFactory.newFactory();

        FileReader reader = new FileReader("input.xml");
        XMLStreamReader xsr = xif.createXMLStreamReader(reader);

        JAXBContext jc = JAXBContext.newInstance(Customer.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();

        while(xsr.hasNext()) {
            while(xsr.hasNext() && (!xsr.isStartElement() || !xsr.getLocalName().equals("customer"))) {

                xsr.next();
            }
            if(xsr.hasNext()) {
                Customer customer = (Customer) unmarshaller.unmarshal(xsr);
                System.out.println(customer);
            }
        }

    }

}
查看更多
Luminary・发光体
3楼-- · 2020-04-30 03:21

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.

查看更多
可以哭但决不认输i
4楼-- · 2020-04-30 03:22

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> customer;          // List is much better than array
  public List<Customer> 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.

查看更多
登录 后发表回答