先簡單說下前三種方式:
DOM方式:個人理解類似.net的XmlDocument,解析的時候效率不高,佔用內存,不適合大XML的解析;
SAX方式:基於事件的解析,當解析到xml的某個部分的時候,會觸發特定事件,可以在自訂的解析類別中定義當事件觸發時要做得事情;個人感覺一種很另類的方式,不知道.Net系統下是否有沒有類似的方式?
StAX方式:個人理解類似.net的XmlReader方式,效率高,佔用內存少,適用大XML的解析;
不過SAX方式之前也用過,本文主要介紹JAXB,這裡只貼下主要代碼:
import java.util.ArrayList; import java.util.List; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class ConfigParser extends DefaultHandler { private String currentConfigSection; public SysConfigItem sysConfig; public List<InterfaceConfigItem> interfaceConfigList; public List<FtpConfigItem> ftpConfigList; public List<AdapterConfigItem> adapterConfigList; public void startDocument() throws SAXException { sysConfig = new SysConfigItem(); interfaceConfigList = new ArrayList<InterfaceConfigItem>(); ftpConfigList = new ArrayList<FtpConfigItem>(); adapterConfigList = new ArrayList<AdapterConfigItem>(); } public void endDocument() throws SAXException { } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("Item") && attributes.getLength() > 0) { if (currentConfigSection.equalsIgnoreCase("SysConfigItem")) { sysConfig = new SysConfigItem(attributes); } else if (currentConfigSection.equalsIgnoreCase("InterfaceConfigItems")) { interfaceConfigList.add(new InterfaceConfigItem(attributes)); } else if (currentConfigSection.equalsIgnoreCase("FtpConfigItems")) { ftpConfigList.add(new FtpConfigItem(attributes)); } else if (currentConfigSection.equalsIgnoreCase("AdapterConfigItems")) { adapterConfigList.add(new AdapterConfigItem(attributes)); } } else { currentConfigSection = qName; } } public void endElement(String uri, String localName, String qName) throws SAXException { } public void characters(char ch[], int start, int length) throws SAXException { } }
import java.lang.reflect.Field; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.xml.sax.Attributes; public class ConfigItemBase { private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public ConfigItemBase() { } /** * 目前只支持几种常用类型 如果需要支持其他类型,请修改这里的代码 * * @param attributes */ public ConfigItemBase(Attributes attributes) { Class<?> cls = this.getClass(); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { String fieldType = field.getType().getSimpleName(); for (int i = 0; i < attributes.getLength(); i++) { if (attributes.getQName(i).equalsIgnoreCase(field.getName())) { field.setAccessible(true); try { if (fieldType.equalsIgnoreCase("String")) { field.set(this, attributes.getValue(attributes.getQName(i))); } else if (fieldType.equalsIgnoreCase("Integer")) { 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("Date")) { field.set(this, GetDate(attributes.getValue(attributes.getQName(i)))); } else { System.out.println("Warning:Unhandler Field(" + field.getName() + "-" + fieldType + ")"); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } break; } } } } public String toString() { String result = ""; Class<?> cls = this.getClass(); String classNameString = cls.getName(); result += classNameString.substring(classNameString.lastIndexOf('.') + 1, classNameString.length()) + ":"; Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { try { result += field.getName() + "=" + field.get(this) + ";"; } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return result; } /** * 处理时间类型属性(时间格式要求为:yyyy-MM-dd hh:mm:ss) * * @param dateString * @return */ private static Date GetDate(String dateString) { Date date = null; try { date = dateFormat.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } return date; } }
下面重點介紹一下最方便的:JAXB(Java Architecture for XML Binding)
這裡用比較複雜的移動BatchSyncOrderRelationReq接口XML做為示例(感覺能解這個大家基本上夠用了),報文格式如下(SvcCont裡的CDATA內容是報文體,太噁心了):
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <InterBOSS> <Version>0100</Version> <TestFlag>0</TestFlag> <BIPType> <BIPCode>BIP2B518</BIPCode> <ActivityCode>T2101518</ActivityCode> <ActionCode>0</ActionCode> </BIPType> <RoutingInfo> <OrigDomain>BOSS</OrigDomain> <RouteType>routeType</RouteType> <Routing> <HomeDomain>XXXX</HomeDomain> <RouteValue>routeValue</RouteValue> </Routing> </RoutingInfo> <TransInfo> <SessionID>2013041017222313925676</SessionID> <TransIDO>2013041017222313925676</TransIDO> <TransIDOTime>20130410172223</TransIDOTime> <TransIDH></TransIDH> <TransIDHTime></TransIDHTime> </TransInfo> <SNReserve> <TransIDC></TransIDC> <ConvID></ConvID> <CutOffDay></CutOffDay> <OSNTime></OSNTime> <OSNDUNS></OSNDUNS> <HSNDUNS></HSNDUNS> <MsgSender></MsgSender> <MsgReceiver></MsgReceiver> <Priority></Priority> <ServiceLevel></ServiceLevel> <SvcContType></SvcContType> </SNReserve> <Response> <RspType>rspType</RspType> <RspCode>rspCode</RspCode> <RspDesc>rspDesc</RspDesc> </Response> <SvcCont><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <batchSyncOrderRelationReq> <msgTransactionID>210001BIP2B518130410172223651627</msgTransactionID> <reqNum>2</reqNum> <reqBody> <oprNumb>210001BIP2B518130410172224341871</oprNumb> <subscriptionInfo> <oprTime>oprTime1</oprTime> <actionID>actionId1</actionID> <brand>brand1</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>feeType1</feeType> </subscriptionInfo> </reqBody> <reqBody> <oprNumb>210001BIP2B518130410172224420909</oprNumb> <subscriptionInfo> <oprTime>oprTime2</oprTime> <actionID>actionId2</actionID> <brand>brand2</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> </InterBOSS>
解碼代碼如下:
@XmlRootElement(name = "batchSyncOrderRelationReq") @XmlAccessorType(XmlAccessType.FIELD) public class BatchSyncOrderRelationReq extends BossMessage<BatchSyncOrderRelationReq> { @XmlElement(name = "msgTransactionID") private String msgTransactionId = ""; @XmlElement(name = "reqNum") private String reqNum = ""; @XmlElement(name = "reqBody") private List<BatchSyncOrderRelationReqBody> reqBodyList; public BatchSyncOrderRelationReq() { } public String getMsgTransactionId() { return this.msgTransactionId; } public void setMsgTransactionId(String msgTransactionId) { this.msgTransactionId = msgTransactionId; } public String getReqNum() { return this.reqNum; } public void setReqNum(String reqNum) { this.reqNum = reqNum; } public List<BatchSyncOrderRelationReqBody> getReqBodyList() { return this.reqBodyList; } public void setReqBodyList(List<BatchSyncOrderRelationReqBody> reqBodyList) { this.reqBodyList = reqBodyList; } @Override public BatchSyncOrderRelationReq Deserialized(String interBossXmlContent) throws BusinessException { try { // deserialized for head JAXBContext jaxbCxt4Head = JAXBContext.newInstance(MessageHead.class); Unmarshaller unmarshaller4Head = jaxbCxt4Head.createUnmarshaller(); MessageHead head = (MessageHead) unmarshaller4Head.unmarshal(new StringReader(interBossXmlContent)); // deserialized for SyncOrderRelationReq body JAXBContext jaxbCxt4Body = JAXBContext.newInstance(BatchSyncOrderRelationReq.class); Unmarshaller unmarshaller4Body = jaxbCxt4Body.createUnmarshaller(); BatchSyncOrderRelationReq batchSyncOrderRelationReq = (BatchSyncOrderRelationReq) unmarshaller4Body.unmarshal(new StringReader(head.getSvcCont().trim())); batchSyncOrderRelationReq.setHead(head); return batchSyncOrderRelationReq; } catch (JAXBException e) { throw new BusinessException("SyncOrderRelationReq.Deserialized() Error!(" + interBossXmlContent + ")", e); } } }
@XmlAccessorType(XmlAccessType.FIELD) public class BatchSyncOrderRelationReqBody { @XmlElement(name = "oprNumb") private String oprNumb = ""; @XmlElement(name = "subscriptionInfo") private SubscriptionInfo subscriptionInfo; public BatchSyncOrderRelationReqBody(){ } public BatchSyncOrderRelationReqBody(String oprNumb, SubscriptionInfo subscriptionInfo) { this.oprNumb = oprNumb; this.subscriptionInfo = subscriptionInfo; } public String getOprNumb() { return this.oprNumb; } public void setOprNumb(String oprNumb) { this.oprNumb = oprNumb; } public SubscriptionInfo getSubscriptionInfo() { return this.subscriptionInfo; } public void setSubscriptionInfo(SubscriptionInfo subscriptionInfo) { this.subscriptionInfo = subscriptionInfo; } }
@XmlAccessorType(XmlAccessType.FIELD) public class SubscriptionInfo { @XmlElement(name = "oprTime") private String oprTime = ""; @XmlElement(name = "actionID") private String actionId = ""; @XmlElement(name = "brand") private String brand = ""; @XmlElement(name = "effTime") private String effTime = ""; @XmlElement(name = "expireTime") private String expireTime = ""; @XmlElement(name = "feeUser_ID") private String feeUserId = ""; @XmlElement(name = "destUser_ID") private String destUserId = ""; @XmlElement(name = "actionReasonID") private String actionReasonId = ""; @XmlElement(name = "servType") private String servType = ""; @XmlElement(name = "subServType") private String subServType = ""; @XmlElement(name = "SPID") private String spId = ""; @XmlElement(name = "SPServID") private String spServId = ""; @XmlElement(name = "accessMode") private String accessMode = ""; @XmlElement(name = "feeType") private String feeType = ""; public SubscriptionInfo() { } public SubscriptionInfo( String oprTime, String actionId, String brand, String effTime, String expireTime, String feeUserId, String destUserId, String actionReasonId, String servType, String subServType, String spId, String spServId, String accessMode, String feeType) { this.oprTime = oprTime; this.actionId = actionId; this.brand = brand; this.effTime = effTime; this.expireTime = expireTime; this.feeUserId = feeUserId; this.destUserId = destUserId; this.actionReasonId = actionReasonId; this.servType = servType; this.subServType = subServType; this.spId = spId; this.spServId = spServId; this.accessMode = accessMode; this.feeType = feeType; } public String getOprTime() { return this.oprTime; } public void setOprTime(String oprTime) { this.oprTime = oprTime; } public String getActionId() { return this.actionId; } public void setActionId(String actionId) { this.actionId = actionId; } public String getBrand() { return this.brand; } public void setBrand(String brand) { this.brand = brand; } public String getEffTime() { return this.effTime; } public void setEffTime(String effTime) { this.effTime = effTime; } public String getExpireTime() { return this.expireTime; } public void setExpireTime(String expireTime) { this.expireTime = expireTime; } public String getFeeUserId() { return this.feeUserId; } public void setFeeUserId(String feeUserId) { this.feeUserId = feeUserId; } public String getDestUserId() { return this.destUserId; } public void setDestUserId(String destUserId) { this.destUserId = destUserId; } public String getActionReasonId() { return this.actionReasonId; } public void setActionReasonId(String actionReasonId) { this.actionReasonId = actionReasonId; } public String getServType() { return this.servType; } public void setServType(String servType) { this.servType = servType; } public String getSubServType() { return this.subServType; } public void setSubServType(String subServType) { this.subServType = subServType; } public String getSpId() { return this.spId; } public void setSpId(String spId) { this.spId = spId; } public String getSpServId() { return this.spServId; } public void setSpServId(String spServId) { this.spServId = spServId; } public String getAccessMode() { return this.accessMode; } public void setAccessMode(String accessMode) { this.accessMode = accessMode; } public String getFeeType() { return this.feeType; } public void setFeeType(String feeType) { this.feeType = feeType; } }
更多Java中對XML的解析詳解相關文章請關注PHP中文網!

rssfeedsarexmldocuments usedforcontentAggregation and distribution.totransformthemintoreadableContent:1)parsethethexmlusinglibrarieslibrariesliblarieslikeparserinparserinpython.2)andledifferentifferentrssssssssssssssssssssssssssssssssssssssssssssssersions andpotentionparsingrorS.3)

JSONFeed是一種基於JSON的RSS替代方案,其優勢在於簡潔性和易用性。 1)JSONFeed使用JSON格式,易於生成和解析。 2)它支持動態生成,適用於現代Web開發。 3)使用JSONFeed可以提升內容管理效率和用戶體驗。

如何構建、驗證和發布RSSfeeds? 1.構建:使用Python腳本生成RSSfeed,包含標題、鏈接、描述和發布日期。 2.驗證:使用FeedValidator.org或Python腳本檢查RSSfeed是否符合RSS2.0標準。 3.發布:將RSS文件上傳到服務器,或使用Flask動態生成並發布RSSfeed。通過這些步驟,你可以有效管理和分享內容。

確保XML/RSSfeeds安全性的方法包括:1.數據驗證,2.加密傳輸,3.訪問控制,4.日誌和監控。這些措施通過網絡安全協議、數據加密算法和訪問控制機制來保護數據的完整性和機密性。

XML是一種標記語言,用於存儲和傳輸數據,RSS是一種基於XML的格式,用於發布頻繁更新的內容。 1)XML通過標籤和屬性描述數據結構,2)RSS定義特定標籤發布和訂閱內容,3)使用Python的xml.etree.ElementTree模塊可以創建和解析XML,4)XPath表達式可查詢XML節點,5)feedparser庫可解析RSSfeed,6)常見錯誤包括標籤不匹配和編碼問題,可用xmllint驗證,7)使用SAX解析器處理大型XML文件可優化性能。

XML是一種用於數據存儲和交換的標記語言,RSS是基於XML的格式,用於發布更新內容。 1.XML定義數據結構,適合數據交換和存儲。 2.RSS用於內容訂閱,解析時使用專門庫。 3.解析XML可使用DOM或SAX,生成XML和RSS需正確設置元素和屬性。

使用Python可以從XML/RSS轉換到JSON。 1)解析源數據,2)提取字段,3)轉換為JSON,4)輸出JSON。使用xml.etree.ElementTree和feedparser庫解析XML/RSS,使用json庫生成JSON數據。

XML/RSS和RESTAPI在現代網絡開發中協同工作,通過以下方式:1)XML/RSS用於內容髮布和訂閱,2)RESTAPI用於設計和操作網絡服務。結合使用這兩者可以實現高效的內容管理和動態更新。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Dreamweaver Mac版
視覺化網頁開發工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

WebStorm Mac版
好用的JavaScript開發工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)