처음 세 가지 방법에 대해 간략하게 설명하겠습니다.
DOM 방식 : 저는 개인적으로 .net과 유사한 XmlDocument가 구문 분석 시 효율적이지 않고 메모리를 차지하며 대규모 XML 구문 분석에 적합하지 않다는 것을 이해합니다.
SAX 방식 : 이벤트 기반 구문 분석 xml의 특정 부분이 구문 분석될 때 특정 이벤트가 트리거될 때 사용자 정의 구문 분석 클래스에서 이벤트가 트리거될 때 수행할 작업을 정의할 수 있습니다. 방법. .Net 시스템에도 비슷한 방법이 있는지 궁금합니다.
StAX 방법 : 저는 개인적으로 이 방법이 .net의 XmlReader 방법과 유사하다고 이해합니다. 이 방법은 매우 효율적이고 메모리를 덜 차지하며 대규모 XML을 구문 분석하는 데 적합합니다.
그러나 이전에는 SAX 방법이 사용되었습니다. 이 기사에서는 주로 JAXB를 소개합니다.
다음과 같이 코드 코드를 복사합니다 .
import java.util.ArrayList;
java.util.List 가져오기;
org.xml.sax.Attributes 가져오기;
import org.xml.sax.SAXException;
org.xml.sax.helpers.DefaultHandler 가져오기;
공개 클래스 ConfigParser는 DefaultHandler를 확장합니다.
개인 문자열 currentConfigSection;
공개 SysConfigItem sysConfig;
공개 목록<InterfaceConfigItem> 인터페이스ConfigList;
공개 목록<FtpConfigItem> ftpConfigList;
공개 목록<AdapterConfigItem>adapterConfigList;
public void startDocument()에서 SAXException이 발생합니다.
sysConfig = 새로운 SysConfigItem();
interfaceConfigList = new ArrayList<InterfaceConfigItem>();
ftpConfigList = new ArrayList<FtpConfigItem>();
AdapterConfigList = new ArrayList<AdapterConfigItem>();
}
public void endDocument()에서 SAXException이 발생합니다.
}
public void startElement(String uri, String localName, String qName, Attributes attribute)는 SAXException을 발생시킵니다.
if (qName.equalsIgnoreCase("Item") && attribute.getLength() > 0) {
if (currentConfigSection.equalsIgnoreCase("SysConfigItem")) {
sysConfig = 새로운 SysConfigItem(속성);
} else if (currentConfigSection.equalsIgnoreCase("InterfaceConfigItems")) {
interfaceConfigList.add(new InterfaceConfigItem(속성));
} else if (currentConfigSection.equalsIgnoreCase("FtpConfigItems")) {
ftpConfigList.add(새 FtpConfigItem(속성));
} else if (currentConfigSection.equalsIgnoreCase("AdapterConfigItems")) {
AdapterConfigList.add(새 AdapterConfigItem(속성));
}
} 또 다른 {
currentConfigSection = q이름;
}
}
public void endElement(String uri, String localName, String qName)는 SAXException을 발생시킵니다.
}
공개 무효 문자(char ch[], int start, int length)는 SAXException을 발생시킵니다.
}
}
다음과 같이 코드 코드를 복사합니다 .
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
java.util.Date 가져오기;
org.xml.sax.Attributes 가져오기;
공개 클래스 ConfigItemBase {
private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
공개 ConfigItemBase() {
}
/**
* 현재는 몇 가지 일반적인 유형만 지원됩니다. 다른 유형을 지원해야 하는 경우 여기에서 코드를 수정하세요.
*
* @param 속성
*/
공개 ConfigItemBase(속성 속성) {
클래스<?> cls = this.getClass();
Field[] 필드 = cls.getDeclaredFields();
for (필드 필드 : 필드) {
문자열 fieldType = field.getType().getSimpleName();
for (int i = 0; i < attribute.getLength(); i++) {
if (attributes.getQName(i).equalsIgnoreCase(field.getName())) {
field.setAccessible(true);
노력하다 {
if (fieldType.equalsIgnoreCase("String")) {
field.set(this, attribute.getValue(attributes.getQName(i)));
} else if (fieldType.equalsIgnoreCase("정수")) {
field.set(this, Integer.valueOf(attributes.getValue(attributes.getQName(i))));
} else if (fieldType.equalsIgnoreCase("Double")) {
field.set(this, Double.valueOf(attributes.getValue(attributes.getQName(i))));
} else if (fieldType.equalsIgnoreCase("날짜")) {
field.set(this, GetDate(attributes.getValue(attributes.getQName(i))));
} 또 다른 {
System.out.println("경고:Unhandler Field(" + field.getName() + "-" + fieldType + ")");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
부서지다;
}
}
}
}
공개 문자열 toString() {
문자열 결과 = "";
클래스<?> cls = this.getClass();
String classNameString = cls.getName();
결과 += classNameString.substring(classNameString.lastIndexOf('.') + 1, classNameString.length()) + ":";
Field[] 필드 = cls.getDeclaredFields();
for (필드 필드 : 필드) {
노력하다 {
결과 += field.getName() + "=" + field.get(this) + ";";
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
결과 반환;
}
/**
* 처리 시간 유형 속성(시간 형식 요구 사항: yyyy-MM-dd hh:mm:ss)
*
* @param 날짜문자열
* @반품
*/
개인 정적 날짜 GetDate(String dateString) {
날짜 날짜 = null;
노력하다 {
날짜 = dateFormat.parse(dateString);
} 잡기(ParseException e) {
e.printStackTrace();
}
귀국일;
}
}
다음은 가장 편리한 것에 중점을 둡니다: JAXB(Java Architecture for XML Binding)
여기서는 더 복잡한 모바일 BatchSyncOrderRelationReq 인터페이스 XML을 예로 사용합니다(이것을 이해할 수 있는 모든 사람이 기본적으로 충분하다고 생각합니다). 메시지 형식은 다음과 같습니다(SvcCont의 CDATA 콘텐츠는 역겨운 메시지 본문입니다).
다음과 같이 코드 코드를 복사합니다 .
<?xml version="1.0" 인코딩="UTF-8" 독립형="예" ?>
<인터보스>
<버전>0100</버전>
<TestFlag>0</TestFlag>
<BIP 유형>
<BIPCode>BIP2B518</BIPCode>
<ActivityCode>T2101518</ActivityCode>
<ActionCode>0</ActionCode>
</BIP유형>
<라우팅정보>
<OrigDomain>보스</OrigDomain>
<RouteType>경로 유형</RouteType>
<라우팅>
<HomeDomain>XXXX</HomeDomain>
<RouteValue>경로값</RouteValue>
</라우팅>
</RoutingInfo>
<트랜스포포>
<세션ID>2013041017222313925676</세션ID>
<TransIDO>2013041017222313925676</TransIDO>
<TransIDOTime>20130410172223</TransIDOTime>
<트랜IDH></트랜스IDH>
<TransIDHTime></TransIDHTime>
</TransInfo>
<SN예약>
<트랜스IDC></트랜스IDC>
<ConvID></ConvID>
<CutOffDay></CutOffDay>
<OSN시간></OSN시간>
<OSNDUNS></OSNDUNS>
<HSNDUNS></HSNDUNS>
<MsgSender></MsgSender>
<MsgReceiver></MsgReceiver>
<우선순위></우선순위>
<서비스레벨></서비스레벨>
<SvcContType></SvcContType>
</SN예약>
<응답>
<RspType>rsp유형</RspType>
<RspCode>rspCode</RspCode>
<RspDesc>rspDesc</RspDesc>
</응답>
<SvcCont><![CDATA[<?xml version="1.0" 인코딩="UTF-8" 독립형="예"?>
<batchSyncOrderRelationReq>
<msgTransactionID>210001BIP2B518130410172223651627</msgTransactionID>
<reqNum>2</reqNum>
<요구본문>
<oprNumb>210001BIP2B518130410172224341871</oprNumb>
<구독정보>
<oprTime>oprTime1</oprTime>
<actionID>actionId1</actionID>
<brand>브랜드1</brand>
<effTime>effTime1</effTime>
<expireTime>expireTime1</expireTime>
<feeUser_ID>feeUserId1</feeUser_ID>
<destUser_ID>destUserId1</destUser_ID>
<actionReasonID>actionId1</actionReasonID>
<servType>servType1</servType>
<subServType>subServType1</subServType>
<SPID>spId1</SPID>
<SPServID>spServId1</SPServID>
<accessMode>accessMode1</accessMode>
<servParamInfo>
<para_num>0</para_num>
<para_info>
<para_name></para_name>
<para_value></para_value>
</para_info>
</servParamInfo>
<feeType>수수료 유형1</feeType>
</subscriptionInfo>
</reqBody>
<요구본문>
<oprNumb>210001BIP2B518130410172224420909</oprNumb>
<구독정보>
<oprTime>oprTime2</oprTime>
<actionID>actionId2</actionID>
<brand>브랜드2</brand>
<effTime>effTime2</effTime>
<expireTime>expireTime2</expireTime>
<feeUser_ID>feeUserId2</feeUser_ID>
<destUser_ID>destUserId2</destUser_ID>
<actionReasonID>actionId2</actionReasonID>
<servType>servType2</servType>
<subServType>subServType2</subServType>
<SPID>spId2</SPID>
<SPServID>spServId2</SPServID>
<accessMode>accessMode2</accessMode>
<servParamInfo>
<para_num>0</para_num>
<para_info>
<para_name></para_name>
<para_value></para_value>
</para_info>
</servParamInfo>
<feeType>feeType2</feeType>
</subscriptionInfo>
</reqBody>
</batchSyncOrderRelationReq>]]></SvcCont>
</인터보스>
디코딩 코드는 다음과 같습니다.
다음과 같이 코드 코드를 복사합니다 .
@XmlRootElement(이름 = "batchSyncOrderRelationReq")
@XmlAccessorType(XmlAccessType.FIELD)
공개 클래스 BatchSyncOrderRelationReq는 BossMessage<BatchSyncOrderRelationReq>를 확장합니다.
@XmlElement(이름 = "msgTransactionID")
개인 문자열 msgTransactionId = "";
@XmlElement(이름 = "reqNum")
개인 문자열 reqNum = "";
@XmlElement(이름 = "reqBody")
개인 목록<BatchSyncOrderRelationReqBody> reqBodyList;
공개 BatchSyncOrderRelationReq() {
}
공개 문자열 getMsgTransactionId() {
this.msgTransactionId를 반환합니다.
}
공개 무효 setMsgTransactionId(String msgTransactionId) {
this.msgTransactionId = msgTransactionId;
}
공개 문자열 getReqNum() {
this.reqNum을 반환합니다.
}
공공 무효 setReqNum(String reqNum) {
this.reqNum = reqNum;
}
공개 목록<BatchSyncOrderRelationReqBody> getReqBodyList() {
this.reqBodyList를 반환합니다.
}
공공 무효 setReqBodyList(List<BatchSyncOrderRelationReqBody> reqBodyList) {
this.reqBodyList = reqBodyList;
}
@보수
공개 BatchSyncOrderRelationReq Deserialized(String interBossXmlContent)에서 BusinessException이 발생합니다.
노력하다 {
// 헤드에 대해 역직렬화됨
JAXBContext jaxbCxt4Head = JAXBContext.newInstance(MessageHead.class);
언마샬러 unmarshaller4Head = jaxbCxt4Head.createUnmarshaller();
MessageHead 헤드 = (MessageHead) unmarshaller4Head.unmarshal(new StringReader(interBossXmlContent));
// SyncOrderRelationReq 본문에 대해 역직렬화됨
JAXBContext jaxbCxt4Body = JAXBContext.newInstance(BatchSyncOrderRelationReq.class);
언마샬러 unmarshaller4Body = jaxbCxt4Body.createUnmarshaller();
BatchSyncOrderRelationReq 배치SyncOrderRelationReq = (BatchSyncOrderRelationReq) unmarshaller4Body.unmarshal(new StringReader(head.getSvcCont().trim()));
BatchSyncOrderRelationReq.setHead(head);
BatchSyncOrderRelationReq를 반환합니다.
} 잡기(JAXBException e) {
throw new BusinessException("SyncOrderRelationReq.Deserialized() Error!(" + interBossXmlContent + ")", e);
}
}
}
@XmlAccessorType(XmlAccessType.FIELD)
다음과 같이 코드 코드를 복사합니다 .
공개 클래스 BatchSyncOrderRelationReqBody {
@XmlElement(이름 = "oprNumb")
개인 문자열 oprNumb = "";
@XmlElement(이름 = "subscriptionInfo")
비공개 SubscriptionInfo 구독정보;
공개 BatchSyncOrderRelationReqBody(){
}
공개 BatchSyncOrderRelationReqBody(String oprNumb, SubscriptionInfo subscribeInfo) {
this.oprNumb = oprNumb;
this.subscriptionInfo = 구독정보;
}
공개 문자열 getOprNumb() {
this.oprNumb를 반환합니다.
}
공공 무효 setOprNumb(String oprNumb) {
this.oprNumb = oprNumb;
}
공개 구독정보 getSubscriptionInfo() {
this.subscriptionInfo를 반환합니다.
}
공공 무효 setSubscriptionInfo(SubscriptionInfo subscribeInfo) {
this.subscriptionInfo = 구독정보;
}
}
@XmlAccessorType(XmlAccessType.FIELD)
다음과 같이 코드 코드를 복사합니다 .
공개 클래스 SubscriptionInfo {
@XmlElement(이름 = "oprTime")
개인 문자열 oprTime = "";
@XmlElement(이름 = "actionID")
개인 문자열 actionId = "";
@XmlElement(이름 = "브랜드")
개인 문자열 브랜드 = "";
@XmlElement(이름 = "effTime")
개인 문자열 effTime = "";
@XmlElement(이름 = "expireTime")
개인 문자열 만료 시간 = "";
@XmlElement(이름 = "feeUser_ID")
개인 문자열 feeUserId = "";
@XmlElement(이름 = "destUser_ID")
개인 문자열 destUserId = "";
@XmlElement(이름 = "actionReasonID")
개인 문자열 actionReasonId = "";
@XmlElement(이름 = "servType")
개인 문자열 servType = "";
@XmlElement(이름 = "subServType")
개인 문자열 subServType = "";
@XmlElement(이름 = "SPID")
개인 문자열 spId = "";
@XmlElement(이름 = "SPServID")
개인 문자열 spServId = "";
@XmlElement(이름 = "액세스 모드")
개인 문자열 accessMode = "";
@XmlElement(name = "feeType")
개인 문자열 feeType = "";
공개 구독정보() {
}
공개 구독정보(
문자열 oprTime,
문자열 actionId,
스트링 브랜드,
문자열 effTime,
문자열 만료 시간,
문자열 feeUserId,
문자열 destUserId,
문자열 actionReasonId,
문자열 서비스 유형,
문자열 subServType,
문자열 spId,
문자열 spServId,
문자열 액세스 모드,
문자열 수수료 유형) {
this.oprTime = oprTime;
this.actionId = actionId;
this.brand = 브랜드;
this.effTime = effTime;
this.expireTime = 만료시간;
this.feeUserId = feeUserId;
this.destUserId = destUserId;
this.actionReasonId = actionReasonId;
this.servType = servType;
this.subServType = subServType;
this.spId = spId;
this.spServId = spServId;
this.accessMode = 액세스모드;
this.feeType = 수수료유형;
}
공개 문자열 getOprTime() {
this.oprTime을 반환합니다.
}
공공 무효 setOprTime(문자열 oprTime) {
this.oprTime = oprTime;
}
공개 문자열 getActionId() {
this.actionId를 반환합니다.
}
공공 무효 setActionId(문자열 actionId) {
this.actionId = actionId;
}
공개 문자열 getBrand() {
return this.brand;
}
public void setBrand(문자열 브랜드) {
this.brand = 브랜드;
}
공개 문자열 getEffTime() {
this.effTime을 반환합니다.
}
공공 무효 setEffTime(문자열 effTime) {
this.effTime = effTime;
}
공개 문자열 getExpireTime() {
this.expireTime을 반환합니다.
}
공공 무효 setExpireTime(문자열 만료 시간) {
this.expireTime = 만료시간;
}
공개 문자열 getFeeUserId() {
this.feeUserId를 반환합니다.
}
공공 무효 setFeeUserId(String feeUserId) {
this.feeUserId = feeUserId;
}
공개 문자열 getDestUserId() {
this.destUserId를 반환합니다.
}
공공 무효 setDestUserId(String destUserId) {
this.destUserId = destUserId;
}
공개 문자열 getActionReasonId() {
this.actionReasonId를 반환합니다.
}
공개 무효 setActionReasonId(String actionReasonId) {
this.actionReasonId = actionReasonId;
}
공개 문자열 getServType() {
this.servType을 반환합니다.
}
공공 무효 setServType(String servType) {
this.servType = servType;
}
공개 문자열 getSubServType() {
this.subServType을 반환합니다.
}
공공 무효 setSubServType(String subServType) {
this.subServType = subServType;
}
공개 문자열 getSpId() {
this.spId를 반환합니다.
}
공공 무효 setSpId(문자열 spId) {
this.spId = spId;
}
공개 문자열 getSpServId() {
this.spServId를 반환합니다.
}
공공 무효 setSpServId(String spServId) {
this.spServId = spServId;
}
공개 문자열 getAccessMode() {
this.accessMode를 반환합니다.
}
공공 무효 setAccessMode(문자열 accessMode) {
this.accessMode = 액세스모드;
}
공개 문자열 getFeeType() {
this.feeType을 반환합니다.
}
공공 무효 setFeeType(문자열 feeType) {
this.feeType = 수수료유형;
}
}