最近遇到XML转对象进行业务操作的问题
这是我需要解析的XML
1,建XML对应自己需要参数的Bean。有的很长很乱,没必要全部建,只建自己需要的就行了
import lombok.Data; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import java.util.Date; @Data @XmlRootElement(name = "EventNotificationAlert")//这个是上面图片开头和结尾那个标签名称,你需要替换成你自己的 @XmlAccessorType(XmlAccessType.FIELD) public class EventNotificationAlert { private String ipAddress; private String portNo; private String protocol; private String macAddress;//MAC private String dynChannelID;//2不知道什么 private String channelID; private Date dateTime; private String activePostCount; private String eventType; private String eventState; private String eventDescription; private String deviceID; private String thermalURL; }
2,写解析代码
import com.zhcz.wisdom.yw.eneity.EventNotificationAlert; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.client.RestTemplate; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import java.io.StringReader; public class ToWyServer { @Autowired private RestTemplate restTemplate; public static boolean FireAlarm(String date){ if (StringUtils.isEmpty(date)) return false; System.out.println(date); Object map = ToWyServer.convertXmlStrToObject(EventNotificationAlert.class,date); EventNotificationAlert eee = (EventNotificationAlert) map; System.err.println(eee.toString()); return true; } /**0 * 将String类型的xml转换成对象 */ public static Object convertXmlStrToObject(Class<?> clazz, String xmlStr) { Object xmlObject = null; try { JAXBContext context = JAXBContext.newInstance(clazz); // 进行将Xml转成对象的核心接口 Unmarshaller unmarshal = context.createUnmarshaller(); StringReader sr = new StringReader(xmlStr); xmlObject = unmarshal.unmarshal(sr); } catch (Exception e) { e.printStackTrace(); } return xmlObject; }
完成!