java使用xstream實(shí)現(xiàn)xml文件和對象之間的相互轉(zhuǎn)換
java使用xstream實(shí)現(xiàn)xml文件和對象之間的相互轉(zhuǎn)換
整體描述
xml是一個用途比較廣泛的文件類型,在java里也自帶解析xml的包,但是本文使用的是xstream來實(shí)現(xiàn)xml和對象之間的相互轉(zhuǎn)換,xstream是一個第三方開源框架,使用起來比較方便,xstream官網(wǎng)地址: xstream官網(wǎng),目前最新版本是1.4.19。
具體實(shí)現(xiàn)
1. 引入xstream的maven
添加xstream的依賴,這里使用最新的1.4.19版本
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.19</version>
</dependency>2.xml文件
這里使用的是大疆無人機(jī)的地圖文件template.kml :
xml文件參考文檔:大疆云上API地址: 大疆云上API。
文件具體格式如下,基本包含了xml所有需要使用的示例。
注:文件雖然是.kml格式,但其實(shí)就是xml的格式。
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:wpml="http://www.dji.com/wpmz/1.0.0">
<Document>
<!-- Step 1: Implement File Creation Information -->
<wpml:author>Name</wpml:author>
<wpml:createTime>1637600807044</wpml:createTime>
<wpml:updateTime>1637600875837</wpml:updateTime>
<!-- Step 2: Setup Mission Configuration -->
<wpml:missionConfig>
<wpml:flyToWaylineMode>safely</wpml:flyToWaylineMode>
<wpml:finishAction>goHome</wpml:finishAction>
<wpml:exitOnRCLost>goContinue</wpml:exitOnRCLost>
<wpml:takeOffSecurityHeight>20</wpml:takeOffSecurityHeight>
<wpml:globalTransitionalSpeed>10</wpml:globalTransitionalSpeed>
<wpml:droneInfo>
<!-- Declare drone model with M30 -->
<wpml:droneEnumValue>67</wpml:droneEnumValue>
<wpml:droneSubEnumValue>0</wpml:droneSubEnumValue>
</wpml:droneInfo>
<wpml:payloadInfo>
<!-- Declare payload model with M30 -->
<wpml:payloadEnumValue>52</wpml:payloadEnumValue>
<wpml:payloadSubEnumValue>0</wpml:payloadSubEnumValue>
<wpml:payloadPositionIndex>0</wpml:payloadPositionIndex>
</wpml:payloadInfo>
</wpml:missionConfig>
<!-- Step 3: Setup A Folder for Waypoint Template -->
<Folder>
<wpml:templateType>waypoint</wpml:templateType>
<wpml:useGlobalTransitionalSpeed>0</wpml:useGlobalTransitionalSpeed>
<wpml:templateId>0</wpml:templateId>
<wpml:waylineCoordinateSysParam>
<wpml:coordinateMode>WGS84</wpml:coordinateMode>
<wpml:heightMode>EGM96</wpml:heightMode>
<wpml:ellipsoidHeight>100</wpml:ellipsoidHeight>
<wpml:height>100</wpml:height>
<wpml:positioningType>GPS</wpml:positioningType>
</wpml:waylineCoordinateSysParam>
<wpml:autoFlightSpeed>7</wpml:autoFlightSpeed>
<wpml:transitionalSpeed>7</wpml:transitionalSpeed>
<wpml:gimbalPitchMode>usePointSetting</wpml:gimbalPitchMode>
<wpml:globalWaypointHeadingParam>
<wpml:waypointHeadingMode>followWayline</wpml:waypointHeadingMode>
</wpml:globalWaypointHeadingParam>
<wpml:globalWaypointTurnMode>toPointAndStopWithDiscontinuityCurvature</wpml:globalWaypointTurnMode>
<Placemark>
<Point>
<!-- Fill longitude and latitude here -->
<coordinates>
longitude,latitude
</coordinates>
</Point>
<wpml:index>0</wpml:index>
<wpml:ellipsoidHeight>90.2</wpml:ellipsoidHeight>
<wpml:height>100</wpml:height>
<wpml:useGlobalHeight>1</wpml:useGlobalHeight>
<wpml:useGlobalSpeed>1</wpml:useGlobalSpeed>
<wpml:useGlobalHeadingParam>1</wpml:useGlobalHeadingParam>
<wpml:useGlobalTurnParam>1</wpml:useGlobalTurnParam>
<wpml:gimbalPitchAngle>0</wpml:gimbalPitchAngle>
</Placemark>
<Placemark>
<Point>
<!-- Fill longitude and latitude here -->
<coordinates>
longitude,latitude
</coordinates>
</Point>
<wpml:index>1</wpml:index>
<wpml:ellipsoidHeight>90.2</wpml:ellipsoidHeight>
<wpml:height>100</wpml:height>
<wpml:useGlobalHeight>1</wpml:useGlobalHeight>
<wpml:useGlobalSpeed>1</wpml:useGlobalSpeed>
<wpml:useGlobalHeadingParam>1</wpml:useGlobalHeadingParam>
<wpml:useGlobalTurnParam>1</wpml:useGlobalTurnParam>
<wpml:gimbalPitchAngle>0</wpml:gimbalPitchAngle>
<!-- Declare action group for waypoint 1# -->
<wpml:actionGroup>
<wpml:actionGroupId>0</wpml:actionGroupId>
<wpml:actionGroupStartIndex>1</wpml:actionGroupStartIndex>
<wpml:actionGroupEndIndex>1</wpml:actionGroupEndIndex>
<wpml:actionGroupMode>sequence</wpml:actionGroupMode>
<wpml:actionTrigger>
<wpml:actionTriggerType>reachPoint</wpml:actionTriggerType>
</wpml:actionTrigger>
<!-- Declare the 1st action: rotate gimbal -->
<wpml:action>
<wpml:actionId>0</wpml:actionId>
<wpml:actionActuatorFunc>gimbalRotate</wpml:actionActuatorFunc>
<wpml:actionActuatorFuncParam>
<wpml:gimbalRotateMode>absoluteAngle</wpml:gimbalRotateMode>
<wpml:gimbalPitchRotateEnable>0</wpml:gimbalPitchRotateEnable>
<wpml:gimbalPitchRotateAngle>0</wpml:gimbalPitchRotateAngle>
<wpml:gimbalRollRotateEnable>0</wpml:gimbalRollRotateEnable>
<wpml:gimbalRollRotateAngle>0</wpml:gimbalRollRotateAngle>
<wpml:gimbalYawRotateEnable>1</wpml:gimbalYawRotateEnable>
<wpml:gimbalYawRotateAngle>30</wpml:gimbalYawRotateAngle>
<wpml:gimbalRotateTimeEnable>0</wpml:gimbalRotateTimeEnable>
<wpml:gimbalRotateTime>0</wpml:gimbalRotateTime>
<wpml:payloadPositionIndex>0</wpml:payloadPositionIndex>
</wpml:actionActuatorFuncParam>
</wpml:action>
<!-- Declare the 2nd action: take photo -->
<wpml:action>
<wpml:actionId>1</wpml:actionId>
<wpml:actionActuatorFunc>takePhoto</wpml:actionActuatorFunc>
<wpml:actionActuatorFuncParam>
<wpml:fileSuffix>point1</wpml:fileSuffix>
<wpml:payloadPositionIndex>0</wpml:payloadPositionIndex>
</wpml:actionActuatorFuncParam>
</wpml:action>
</wpml:actionGroup>
</Placemark>
</Folder>
</Document>
</kml>3. 創(chuàng)建相應(yīng)的對象
根據(jù)xml文件的格式,創(chuàng)建出各個節(jié)點(diǎn)的對象,使用xstream的注解實(shí)現(xiàn)設(shè)置標(biāo)簽的功能,這里主要使用以下幾個注解:@XStreamAlias(“kml”):設(shè)置標(biāo)簽,內(nèi)容為對象;@XStreamImplicit(itemFieldName = “Placemark”):設(shè)置標(biāo)簽,內(nèi)容為list@XStreamAsAttribute:標(biāo)簽內(nèi)屬性具體對象類:最外層的Kml對象:
package com.thcb.xml.bean.template;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import lombok.Data;
/**
* Kml
*
* @author nhx
* @date 2022-07-29
*/
@Data
@XStreamAlias("kml")
public class Kml {
@XStreamAlias("xmlns")
@XStreamAsAttribute
private String xmlns;
@XStreamAlias("xmlns:wpml")
@XStreamAsAttribute
private String wpml;
@XStreamAlias("Document")
private Document document;
}Document對象:
package com.thcb.xml.bean.template;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.Data;
/**
* Document
*
* @author nhx
* @date 2022-07-29
*/
@Data
@XStreamAlias("Document")
public class Document {
/**
* 文件創(chuàng)建作者
*/
@XStreamAlias("wpml:author")
private String author;
/**
* 文件創(chuàng)建時間(Unix Timestamp)
*/
@XStreamAlias("wpml:createTime")
private Long createTime;
/**
* 文件更新時間(Unix Timestamp)
*/
@XStreamAlias("wpml:updateTime")
private Long updateTime;
/**
* 任務(wù)信息
*/
@XStreamAlias("wpml:missionConfig")
private MissionConfig missionConfig;
/**
* 模板信息
*/
@XStreamAlias("Folder")
private Folder folder;
}MissionConfig對象:
package com.thcb.xml.bean.template;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.Data;
/**
* MissionConfig
*
* @author nhx
* @date 2022-07-29
*/
@Data
@XStreamAlias("wpml:missionConfig")
public class MissionConfig {
/**
* 飛向首航點(diǎn)模式
*/
@XStreamAlias("wpml:flyToWaylineMode")
private String flyToWaylineMode;
/**
* 航線結(jié)束動作
*/
@XStreamAlias("wpml:finishAction")
private String finishAction;
/**
* 失控是否繼續(xù)執(zhí)行航線
*/
@XStreamAlias("wpml:exitOnRCLost")
private String exitOnRCLost;
/**
* 失控動作類型
*/
@XStreamAlias("wpml:executeRCLostAction")
private String executeRCLostAction;
/**
* 安全起飛高度
*/
@XStreamAlias("wpml:takeOffSecurityHeight")
private String takeOffSecurityHeight;
/**
* 全局航線過渡速度
*/
@XStreamAlias("wpml:globalTransitionalSpeed")
private String globalTransitionalSpeed;
/**
* 參考起飛點(diǎn)
*/
@XStreamAlias("wpml:takeOffRefPoint")
private String takeOffRefPoint;
/**
* 參考起飛點(diǎn)海拔高度
*/
@XStreamAlias("wpml:takeOffRefPointAGLHeight")
private String takeOffRefPointAGLHeight;
@XStreamAlias("wpml:globalRTHHeight")
private String globalRTHHeight;
/**
* 飛行器機(jī)型信息
*/
@XStreamAlias("wpml:droneInfo")
private DroneInfo droneInfo;
/**
* 負(fù)載機(jī)型信息
*/
@XStreamAlias("wpml:payloadInfo")
private PayloadInfo payloadInfo;
}Folder對象:
package com.thcb.xml.bean.template;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import lombok.Data;
import java.util.List;
/**
* Folder
*
* @author nhx
* @date 2022-07-29
*/
@Data
@XStreamAlias("Folder")
public class Folder {
// 模板共用元素
/**
* 預(yù)定義模板類型
*/
@XStreamAlias("wpml:templateType")
private String templateType;
@XStreamAlias("wpml:useGlobalTransitionalSpeed")
private String useGlobalTransitionalSpeed;
/**
* 模板ID
*/
@XStreamAlias("wpml:templateId")
private String templateId;
/**
* 全局航線飛行速度
*/
@XStreamAlias("wpml:autoFlightSpeed")
private String autoFlightSpeed;
@XStreamAlias("wpml:transitionalSpeed")
private String transitionalSpeed;
/**
* 坐標(biāo)系參數(shù)
*/
@XStreamAlias("wpml:waylineCoordinateSysParam")
private WaylineCoordinateSysParam waylineCoordinateSysParam;
/**
* 負(fù)載設(shè)置
*/
@XStreamAlias("wpml:payloadParam")
private PayloadParam payloadParam;
// 航點(diǎn)飛行模板元素
/**
* 全局航點(diǎn)類型(全局航點(diǎn)轉(zhuǎn)彎模式)
*/
@XStreamAlias("wpml:globalWaypointTurnMode")
private String globalWaypointTurnMode;
/**
* 全局航段軌跡是否盡量貼合直線
*/
@XStreamAlias("wpml:globalUseStraightLine")
private String globalUseStraightLine;
/**
* 云臺俯仰角控制模式
*/
@XStreamAlias("wpml:gimbalPitchMode")
private String gimbalPitchMode;
/**
* 全局航線高度(橢球高)
*/
@XStreamAlias("wpml:ellipsoidHeight")
private String ellipsoidHeight;
/**
* 全局航線高度(EGM96海拔高/相對起飛點(diǎn)高度/AGL相對地面高度)
*/
@XStreamAlias("wpml:height")
private String height;
/**
* 全局偏航角模式參數(shù)
*/
@XStreamAlias("wpml:globalWaypointHeadingParam")
private GlobalWaypointHeadingParam globalWaypointHeadingParam;
/**
* 航點(diǎn)信息(包括航點(diǎn)經(jīng)緯度和高度等)
*/
@XStreamImplicit(itemFieldName = "Placemark")
private List<Placemark> placemarkList;
// 建圖航拍模板元素
/**
* 是否開啟標(biāo)定飛行
* 注:僅適用于M300RTK與L1機(jī)型
*/
@XStreamAlias("wpml:caliFlightEnable")
private String caliFlightEnable;
/**
* 是否開啟高程優(yōu)化
*/
@XStreamAlias("wpml:elevationOpimizeEnable")
private String elevationOpimizeEnable;
/**
* 是否開啟智能擺拍
* 注:僅適用于M300RTK與P1機(jī)型
*/
@XStreamAlias("wpml:elevationOpimizeEnable")
private String smartObliqueEnable;
/**
* 智能擺拍拍攝俯仰角
* 注:僅適用于M300RTK與P1機(jī)型。P1機(jī)型云臺建議輸入范圍[-90, -45]
*/
@XStreamAlias("wpml:smartObliqueGimbalPitch")
private String smartObliqueGimbalPitch;
/**
* 拍照模式(定時或定距)
*/
@XStreamAlias("wpml:shootType")
private String shootType;
/**
* 航線方向
*/
@XStreamAlias("wpml:direction")
private String direction;
/**
* 測區(qū)外擴(kuò)距離
*/
@XStreamAlias("wpml:margin")
private String margin;
/**
* 重疊率參數(shù)
*/
@XStreamAlias("wpml:overlap")
private String overlap;
/**
* 全局航線高度(橢球高):ellipsoidHeight
* 全局航線高度(EGM96海拔高/相對起飛點(diǎn)高度/AGL相對地面高度):height
*/
/**
* 測區(qū)多邊形
*/
@XStreamAlias("Polygon")
private Polygon polygon;
// 傾斜攝影模板元素
/**
* 云臺俯仰角度(傾斜)
*/
@XStreamAlias("wpml:inclinedGimbalPitch")
private String inclinedGimbalPitch;
/**
* 航線飛行速度(傾斜)
*/
@XStreamAlias("wpml:inclinedFlightSpeed")
private String inclinedFlightSpeed;
// 航帶飛行模板元素
/**
* 是否開啟單航線飛行
*/
@XStreamAlias("wpml:singleLineEnable")
private String singleLineEnable;
/**
* 每個子航帶航線長度
*/
@XStreamAlias("wpml:cuttingDistance")
private String cuttingDistance;
/**
* 是否開啟邊緣優(yōu)化
*/
@XStreamAlias("wpml:boundaryOptimEnable")
private String boundaryOptimEnable;
/**
* 航帶左側(cè)外擴(kuò)距離
*/
@XStreamAlias("wpml:leftExtend")
private String leftExtend;
/**
* 航帶右側(cè)外擴(kuò)距離
*/
@XStreamAlias("wpml:rightExtend")
private String rightExtend;
/**
* 是否包含中心線
*/
@XStreamAlias("wpml:includeCenterEnable")
private String includeCenterEnable;
/**
* 航點(diǎn)信息
*/
@XStreamAlias("LineString")
private LineString lineString;
/**
* 其他,參數(shù)無具體說明
*/
@XStreamAlias("wpml:globalHeight")
private String globalHeight;
}這里就不把所有對象的代碼都貼出來了,以上幾個已經(jīng)足夠了,剩下的可以舉一反三,自己創(chuàng)建出來。注意:如果想要解析xml,必須要把xml中的所有結(jié)構(gòu)和標(biāo)簽都創(chuàng)建出來才可以,否則會報(bào)錯。
4. 創(chuàng)建xml工具類
創(chuàng)建xml工具類,主要就是將xstream進(jìn)行一個簡單的封裝
package com.thcb.xml.util;
import com.thcb.xml.bean.template.Kml;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
* FileUtils
*
* @author nhx
* @date 2022-08-01
*/
public class XmlUtils {
/**
* xstream初始化
*/
private static final XStream XSTREAM = new XStream(new DomDriver());
/**
* 添加合法的包名,否則無法解析xml,使用時需要改成自己工程的包名
*/
private static final String PACKET = "com.thcb.**";
/**
* 將xml字符串轉(zhuǎn)為Kml對象
*
* @param xmlString xml字符串
*/
public static Kml xmlToKml(String xmlString) {
XSTREAM.allowTypesByWildcard(new String[]{PACKET});
XSTREAM.processAnnotations(Kml.class);
return (Kml) XSTREAM.fromXML(xmlString);
}
/**
* 將Kml對象轉(zhuǎn)為xml字符串
*
* @param kml Kml對象
*/
public static String kmlToXml(Kml kml) {
// 設(shè)置包名
XSTREAM.allowTypesByWildcard(new String[]{PACKET});
// 設(shè)置kml中的xmlns標(biāo)簽
kml.setXmlns("http://www.opengis.net/kml/2.2");
// 設(shè)置kml中的wpml標(biāo)簽
kml.setWpml("http://www.dji.com/wpmz/1.0.0");
// 轉(zhuǎn)換的字符串前面加上xml說明
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + XSTREAM.toXML(kml);
}
}5. 創(chuàng)建讀取/寫入文件工具類
由于需要讀取和寫入文件,這里就創(chuàng)建一個讀寫文件的工具類,便于操作。
package com.thcb.xml.util;
import com.thcb.xml.bean.template.Kml;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
* FileUtils
*
* @author nhx
* @date 2022-08-01
*/
public class XmlUtils {
/**
* xstream初始化
*/
private static final XStream XSTREAM = new XStream(new DomDriver());
/**
* 添加合法的包名,否則無法解析xml,使用時需要改成自己工程的包名
*/
private static final String PACKET = "com.thcb.**";
/**
* 將xml字符串轉(zhuǎn)為Kml對象
*
* @param xmlString xml字符串
*/
public static Kml xmlToKml(String xmlString) {
XSTREAM.allowTypesByWildcard(new String[]{PACKET});
XSTREAM.processAnnotations(Kml.class);
return (Kml) XSTREAM.fromXML(xmlString);
}
/**
* 將Kml對象轉(zhuǎn)為xml字符串
*
* @param kml Kml對象
*/
public static String kmlToXml(Kml kml) {
// 設(shè)置包名
XSTREAM.allowTypesByWildcard(new String[]{PACKET});
// 設(shè)置kml中的xmlns標(biāo)簽
kml.setXmlns("http://www.opengis.net/kml/2.2");
// 設(shè)置kml中的wpml標(biāo)簽
kml.setWpml("http://www.dji.com/wpmz/1.0.0");
// 轉(zhuǎn)換的字符串前面加上xml說明
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + XSTREAM.toXML(kml);
}
}6. xml和對象的轉(zhuǎn)換
好了,上面把需要的都創(chuàng)建完了,這里就可以進(jìn)行轉(zhuǎn)換了,xstream使用起來非常方便,轉(zhuǎn)換過程只需一步:
package com.thcb.test;
import com.thcb.xml.util.FileUtils;
import com.thcb.xml.util.XmlUtils;
import com.thcb.xml.util.ZipUtils;
import com.thcb.xml.bean.template.Kml;
/**
* XmlTest
*
* @author nhx
* @date 2022-07-28
*/
public class XmlTest {
public static void main(String[] args) {
// 讀取文件流
String string = FileUtils.readFile("文件路徑");
try {
// xml字符串轉(zhuǎn)換成對象
Kml kml = XmlUtils.xmlToKml(string);
// log其中的一個屬性值
String coordinates = kml.getDocument().getFolder().getPlacemarkList().get(0).getPoint().getCoordinates().trim();
System.out.println("coordinates:" + coordinates);
// 修改其中幾個屬性值
kml.getDocument().setUpdateTime(System.currentTimeMillis());
kml.getDocument().setAuthor("nhx");
// 對象轉(zhuǎn)換成xml字符串
String xml = XmlUtils.kmlToXml(kml);
// log轉(zhuǎn)換完的xml
System.out.println("xml:\n" + xml);
// 寫入文件
FileUtils.writerFile(xml, "文件路徑", false);
} catch (Exception e) {
System.out.println(e.toString());
}
System.out.println("over");
}
}結(jié)語
至此,xml和對象的互相轉(zhuǎn)換工作就完成了,還是比較簡單的,有興趣的可以看一下xstream的官網(wǎng),在本文開頭就貼出來官網(wǎng)地址了,上面有一些其他用法的介紹。注:舊版本的xstream有安全漏洞,建議使用最新版本。
到此這篇關(guān)于java使用xstream實(shí)現(xiàn)xml文件和對象之間的相互轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)java xml文件和對象轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決MyBatis Mapper的XML文件SQL語句無法自動提示問題(親測有效)
這篇文章主要給大家介紹了如何解決MyBatis Mapper的XML文件SQL語句無法自動提示的問題,文中有詳細(xì)的原因分析,以及通過圖文介紹的解決方案,需要的朋友可以參考下2023-10-10
如何為Spring Cloud Gateway加上全局過濾器
這篇文章主要介紹了如何為Spring Cloud Gateway加上全局過濾器,幫助大家更好得理解和學(xué)習(xí)使用Gateway,感興趣的朋友可以了解下2021-03-03
在SpringBoot中使用ResponseBodyAdvice自定義響應(yīng)的代碼實(shí)現(xiàn)
ResponseBodyAdvice是Spring Framework中的一個接口,允許您在將響應(yīng)寫入客戶端之前自定義響應(yīng),它通常與@ControllerAdvice注釋結(jié)合使用,以跨多個控制器將全局更改應(yīng)用于響應(yīng)主體,本文介紹了如何使用ResponseBodyAdvice的基本概述,需要的朋友可以參考下2024-12-12
java格式化數(shù)字操作 NumberFormat及DecimalFormat
這篇文章主要介紹了java格式化數(shù)字操作 NumberFormat及DecimalFormat,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
spring boot+jwt實(shí)現(xiàn)api的token認(rèn)證詳解
這篇文章主要給大家介紹了關(guān)于spring boot+jwt實(shí)現(xiàn)api的token認(rèn)證的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一學(xué)習(xí)學(xué)習(xí)吧2018-12-12

