将XML从文件序列化为String并返回

时间:2018-06-01 14:22:12

标签: java xml rabbitmq marshalling

我在文件中有这个XML:

<Luggages>
  <luggage>
   <luggageID>1</luggageID>
   <flightID>"1234567"</flightID>
   <conveyorID>19</conveyorID>
   <sensorID>19</sensorID>
   <timeStamp>15.37.58</timeStamp>
  </luggage>
</Luggages>

//other similar elements omitted 

并创建了一个“Luggages”课程

@XmlRootElement(name = "Luggages")
public class Luggages {
    private List<Luggage> luggageList = new ArrayList<>();

    @XmlElement(name = "luggage")
    public List<Luggage> getLuggageList(){
        return luggageList;
    }
    public void setLuggageList(List<Luggage> luggageList) { this.luggageList = luggageList; }
}

行李类:

public class Luggage implements Serializable {
private int luggageID;
private String flightID;
private int conveyorID;
private int sensorID;
private String timeStamp;

public Luggage(LuggageDTO luggageDTO) {
    this.luggageID = luggageDTO.getLuggageID();
    this.flightID = luggageDTO.getFlightID();
    this.conveyorID = luggageDTO.getConveyorID();
    this.sensorID = luggageDTO.getSensorID();
    this.timeStamp = luggageDTO.getTimeStamp();
}
//getters and setters omitted

}

现在,我必须通过RabbitMQ发送这些内容,所以我读取了XML并将其转换为Luggage元素列表:

 public static Luggages readXML(String fileName) throws JAXBException {
    JAXBContext jc = JAXBContext.newInstance(Luggages.class);
    Unmarshaller u = jc.createUnmarshaller();
    File f = new File(fileName);
    return (Luggages) u.unmarshal(f);        
}

然后我将其发送到队列中:

private static void sendLugage(Channel channel, String queue, Logger logger) throws IOException, JAXBException, InterruptedException {

    Luggages luggagelist = Reader.readXML("luggageXML");
    List<Luggage> list = luggagelist.getLuggageList();
    for(Luggage l : list) {           
        channel.basicPublish("", queue, null, l.toString().getBytes());
        logger.info("Luggage with ID " + l.getLuggageID() + " was sent");
        Thread.sleep(2000);
    }
}

现在,在接收端我解组消息

 public Luggage serializeMessage(String message){
    try {
        InputStream stream = new ByteArrayInputStream(message.getBytes());
        return (Luggage) unMarshaller.unmarshal(stream);
    } catch (Exception e) {
        logger.error("Unable to convert String to XML", e);
    }return null;
}

就目前而言,尝试打印出结果:

 System.out.println(message);
 Luggage luggage = serializeMessage(message);
        System.out.println(luggage.getLuggageID());

接收端的行李和行李舱是寄件人的副本。我收到以下错误消息:

Luggage@3930015a
146  [pool-1-thread-4] ERROR domain.Controller  - Unable to convert String to XML
javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.]

我错过了什么?

0 个答案:

没有答案