將對象映射到多個XML模式–天氣示例

我已經在EclipseLink JAXB(MOXy)的@XmlPath和外部綁定文件擴展中撰寫了以前的文章。 在本文中,我將通過將單個對象模型映射到兩個不同的XML模式來演示這些擴展的功能。

為了使示例更加“真實”,XML數據將來自提供天氣信息的兩種不同服務:Google和Yahoo。

Java模型

以下域模型將用于此帖子:

天氣預報

package blog.weather;import java.util.List;public class WeatherReport {private String location;private int currentTemperature;private String currentCondition;private List forecast;}

預測

package blog.weather;public class Forecast {private String dayOfTheWeek;private int low;private int high;private String condition;}

Google Weather API

首先,我們將利用Google的Weather API。 以下URL將用于訪問加拿大渥太華的天氣數據:

http://www.google.com/ig/api?weather=渥太華

以下是在我撰寫本文時執行上述查詢的結果。 我已經突出顯示了我們將映射到XML文檔的部分:

<xml_api_reply version="1"><weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1"row="0" section="0"><forecast_information><city data="Ottawa, ON" /><postal_code data="Ottawa" /><latitude_e6 data="" /><longitude_e6 data="" /><forecast_date data="2011-09-08" /><current_date_time data="2011-09-08 14:00:00 +0000" /><unit_system data="US" /></forecast_information><current_conditions><condition data="Mostly Cloudy" /><temp_f data="66" /><temp_c data="19" /><humidity data="Humidity: 73%" /><icon data="/ig/images/weather/mostly_cloudy.gif" /><wind_condition data="Wind: NE at 13 mph" /></current_conditions><forecast_conditions><day_of_week data="Thu" /><low data="55" /><high data="75" /><icon data="/ig/images/weather/cloudy.gif" /><condition data="Cloudy" /></forecast_conditions><forecast_conditions><day_of_week data="Fri" /><low data="46" /><high data="77" /><icon data="/ig/images/weather/mostly_sunny.gif" /><condition data="Partly Sunny" /></forecast_conditions><forecast_conditions><day_of_week data="Sat" /><low data="43" /><high data="68" /><icon data="/ig/images/weather/sunny.gif" /><condition data="Clear" /></forecast_conditions><forecast_conditions><day_of_week data="Sun" /><low data="55" /><high data="75" /><icon data="/ig/images/weather/sunny.gif" /><condition data="Clear" /></forecast_conditions></weather>
</xml_api_reply>

Java模型-通過注釋映射到Google的XML模式

我們將通過標準JAXB和MOXy擴展注釋的組合來映射Google weather API的結果。

天氣預報

package blog.weather;import java.util.List;import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;import org.eclipse.persistence.oxm.annotations.XmlPath;@XmlRootElement(name="xml_api_reply")
@XmlType(propOrder={"location", "currentCondition", "currentTemperature", "forecast"})
@XmlAccessorType(XmlAccessType.FIELD)
public class WeatherReport {@XmlPath("weather/forecast_information/city/@data")private String location;@XmlPath("weather/current_conditions/temp_f/@data")private int currentTemperature;@XmlPath("weather/current_conditions/condition/@data")private String currentCondition;@XmlPath("weather/forecast_conditions")private List<Forecast> forecast;}

預測

package blog.weather;import org.eclipse.persistence.oxm.annotations.XmlPath;public class Forecast {@XmlPath("day_of_week/@data")private String dayOfTheWeek;@XmlPath("low/@data")private int low;@XmlPath("high/@data")private int high;@XmlPath("condition/@data")private String condition;}

演示版

以下演示代碼將讀取Google氣象服務的XML數據,并將對象編組回XML:

package blog.weather;import java.net.URL;
import javax.xml.bind.*;public class GoogleDemo {public static void main(String[] args) throws Exception {JAXBContext jc = JAXBContext.newInstance(WeatherReport.class);Unmarshaller unmarshaller = jc.createUnmarshaller();URL url = new URL("http://www.google.com/ig/api?weather=Ottawa");WeatherReport weatherReport = (WeatherReport) unmarshaller.unmarshal(url);Marshaller marshaller = jc.createMarshaller();marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);marshaller.marshal(weatherReport, System.out);}}

輸出量

以下是運行演示代碼的結果。 輸出代表我們映射到的XML文檔的一部分:

<?xml version="1.0" encoding="UTF-8"?>
<xml_api_reply><weather><forecast_information><city data="Ottawa, ON"/></forecast_information><current_conditions><condition data="Mostly Cloudy"/><temp_f data="68"/></current_conditions><forecast_conditions><day_of_week data="Thu"/><low data="55"/><high data="75"/><condition data="Cloudy"/></forecast_conditions><forecast_conditions><day_of_week data="Fri"/><low data="46"/><high data="77"/><condition data="Partly Sunny"/></forecast_conditions><forecast_conditions><day_of_week data="Sat"/><low data="43"/><high data="68"/><condition data="Clear"/></forecast_conditions><forecast_conditions><day_of_week data="Sun"/><low data="55"/><high data="75"/><condition data="Clear"/></forecast_conditions></weather>
</xml_api_reply>

雅虎天氣API

以下URL將用于使用Yahoo Weather API(3369是渥太華的WOEID)訪問渥太華的天氣數據:

http://weather.yahooapis.com/forecastrss?w=3369

以下是在我撰寫本文時執行上述查詢的結果:

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"><channel><title>Yahoo! Weather - Ottawa, CA</title><link>http://us.rd.yahoo.com/dailynews/rss/weather/Ottawa__CA/*http://weather.yahoo.com/forecast/CAXX0343_f.html</link><description>Yahoo! Weather for Ottawa, CA</description><language>en-us</language><lastBuildDate>Thu, 08 Sep 2011 10:58 am EDT</lastBuildDate><ttl>60</ttl><yweather:location city="Ottawa" region="ON"country="Canada" /><yweather:units temperature="F" distance="mi" pressure="in"speed="mph" /><yweather:wind chill="66" direction="40" speed="12" /><yweather:atmosphere humidity="73" visibility=""pressure="30.14" rising="0" /><yweather:astronomy sunrise="6:31 am" sunset="7:25 pm" /><image><title>Yahoo! Weather</title><width>142</width><height>18</height><link>http://weather.yahoo.com</link><url>http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif</url></image><item><title>Conditions for Ottawa, CA at 10:58 am EDT</title><geo:lat>45.42</geo:lat><geo:long>-75.69</geo:long><link>http://us.rd.yahoo.com/dailynews/rss/weather/Ottawa__CA/*http://weather.yahoo.com/forecast/CAXX0343_f.html</link><pubDate>Thu, 08 Sep 2011 10:58 am EDT</pubDate><yweather:condition text="Mostly Cloudy" code="28"temp="66" date="Thu, 08 Sep 2011 10:58 am EDT" /><description><![CDATA[
<img src="http://l.yimg.com/a/i/us/we/52/28.gif"/><b>Current Conditions:</b>Mostly Cloudy, 66 F<b>Forecast:</b>Thu - Partly Cloudy. High: 75 Low: 57Fri - Partly Cloudy. High: 79 Low: 53<a href="http://us.rd.yahoo.com/dailynews/rss/weather/Ottawa__CA/*http://weather.yahoo.com/forecast/CAXX0343_f.html">Full Forecast at Yahoo! Weather</a>(provided by <a href="http://www.weather.com" >The Weather Channel</a>)]]></description><yweather:forecast day="Thu" date="8 Sep 2011" low="57"high="75" text="Partly Cloudy" code="30" /><yweather:forecast day="Fri" date="9 Sep 2011" low="53"high="79" text="Partly Cloudy" code="30" /><guid isPermaLink="false">CAXX0343_2011_09_09_7_00_EDT</guid></item></channel>
</rss><!-- api4.weather.sp2.yahoo.com uncompressed/chunked Thu Sep 8 08:32:54PDT 2011 -->

Java模型–通過XML元數據映射到Yahoo的XML模式

由于我們無法通過注釋提供到對象模型的第二套映射,因此我們必須利用MOXy的XML元數據提供后續的映射。 默認情況下,MOXy的映射文檔用于補充模型上指定的所有注釋。 但是,如果設置了xml-mapping-metadata-complete標志,則XML元數據將完全替換注釋提供的元數據(用于Google映射的注釋將保留在POJO上,但是xml-mapping-metadata-complete標志告訴MOXy忽略它們)。

<?xml version="1.0"?>
<xml-bindingsxmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"package-name="blog.weather"xml-mapping-metadata-complete="true"><xml-schema element-form-default="QUALIFIED"><xml-ns prefix="yweather" namespace-uri="http://xml.weather.yahoo.com/ns/rss/1.0"/></xml-schema><java-types><java-type name="WeatherReport" xml-accessor-type="FIELD"><xml-root-element name="rss"/><xml-type prop-order="location currentTemperature currentCondition forecast"/><java-attributes><xml-attribute java-attribute="location" xml-path="channel/yweather:location/@city"/><xml-attribute java-attribute="currentTemperature" name="channel/item/yweather:condition/@temp"/><xml-attribute java-attribute="currentCondition" name="channel/item/yweather:condition/@text"/><xml-element java-attribute="forecast" name="channel/item/yweather:forecast"/></java-attributes></java-type><java-type name="Forecast" xml-accessor-type="FIELD"><java-attributes><xml-attribute java-attribute="dayOfTheWeek" name="day"/><xml-attribute java-attribute="low"/><xml-attribute java-attribute="high"/><xml-attribute java-attribute="condition" name="text"/></java-attributes></java-type></java-types>
</xml-bindings>

演示版

以下演示代碼將讀取Yahoo氣象服務的XML數據,并將對象編組回XML。 由于與未映射的CDATA部分有關的MOXy錯誤(https://bugs.eclipse.org/357145),使用了經過過濾的XMLStreamReader將其從XML輸入中刪除:

package blog.weather;import java.util.HashMap;
import java.util.Map;import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.StreamFilter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.stream.StreamSource;import org.eclipse.persistence.jaxb.JAXBContextFactory;public class YahooDemo {public static void main(String[] args) throws Exception {Map<String, Object> properties = new HashMap<String, Object>(1);properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "blog/weather/yahoo-binding.xml");JAXBContext jc = JAXBContext.newInstance(new Class[] {WeatherReport.class}, properties);XMLInputFactory xif = XMLInputFactory.newFactory();StreamSource xml = new StreamSource("http://weather.yahooapis.com/forecastrss?w=3369");XMLStreamReader xsr = xif.createXMLStreamReader(xml);xsr = xif.createFilteredReader(xsr, new CDATAFilter());Unmarshaller unmarshaller = jc.createUnmarshaller();WeatherReport weatherReport = (WeatherReport) unmarshaller.unmarshal(xsr);Marshaller marshaller = jc.createMarshaller();marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);marshaller.marshal(weatherReport, System.out);}private static class CDATAFilter implements StreamFilter {public boolean accept(XMLStreamReader xsr) {return XMLStreamReader.CDATA != xsr.getEventType();}}}

輸出量

以下是運行演示代碼的結果。 輸出代表我們映射到的XML文檔的一部分:

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"><channel><yweather:location city="Ottawa"/><item><yweather:forecast day="Thu" low="57" high="74" text="Partly Cloudy"/><yweather:forecast day="Fri" low="53" high="79" text="Partly Cloudy"/></item></channel>
</rss>

參考: Java XML和JSON綁定博客上的 JCG合作伙伴 Blaise Doughan的參考:將 對象映射到多個XML模式-天氣示例 。

相關文章 :

  • 使用JAXB從XSD生成XML
  • 具有簡單框架教程的Android XML綁定
  • 使用XML Pull增強Android XML解析
  • 使用Gson教程進行Android JSON解析
  • 用Jackson進行Java JSON處理
  • Java教程和Android教程列表

翻譯自: https://www.javacodegeeks.com/2011/09/mapping-objects-to-multiple-xml-schemas.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/374388.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/374388.shtml
英文地址,請注明出處:http://en.pswp.cn/news/374388.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

STM32F1筆記(九)通用定時器

STM32F1的定時器分為TIME1/8等高級定時器&#xff0c;TIME2~5等通用定時器&#xff0c;TIME6/7基本定時器。三者的區別主要參考《STM32中文參考手冊》里特性的每種定時器主要特性的異同。 先看中文手冊中通用定時器的簡介&#xff1a; 通用定時器的寄存器有一個比較有趣的地方…

佳能MP258的5200錯誤和P08代碼解決方法及清零方法

參考文章轉載于:https://www.cnblogs.com/arcer/p/5659624.html

tomcat通過conf-Catalina-localhost目錄發布項目詳解

轉自&#xff1a;http://www.cnblogs.com/iyangyuan/p/3316444.html&#xff0c;感謝 楊元。 Tomcat發布項目的方式大致有三種&#xff0c;但小菜認為通過在tomcat的conf/Catalina/localhost目錄下添加配置文件&#xff0c;來發布項目&#xff0c;是最佳選擇。 因為這樣對tomca…

c++保存圖標到dll_自動保存郵件附件至指定文件夾

最近有個需求&#xff0c;ERP系統會自動發很多csv附件到我郵箱&#xff0c;我需要把這些附件上傳到FTP服務器&#xff0c;服務器會把這些csv的數據寫到另外一個系統的數據庫。每次大概有30個郵件&#xff0c;每個郵件有一個附件&#xff0c;而且附件的名字都一樣&#xff0c;是…

有時在Java中,一個布局管理器是不夠的

在開發Java Swing應用程序時&#xff0c;最經常的是&#xff0c;我們需要在多個嵌套面板中使用多個布局管理器。 通常這不是問題&#xff0c;并且被認為是幾乎所有人類已知語言的所有UI開發的常規做法。 但是&#xff0c;大多數情況下&#xff0c;對于UI中的每個面板&#xff0…

VM克隆之后啟動eth0找不到eth0:unknown interface:no such device

問題出現&#xff1a;VMware 克隆之后&#xff0c;ifconfig命令執行找不到eth0,報錯 eth0:unknown interface:no such device 是因為/etc/sysconf/network-scripts/ifcfg-eth0配置復制過來和虛擬主機的網卡Mac等信息不匹配 解決方法&#xff1b; 刪除/etc/udev/rules.d/70-pers…

“精彩極了”和“糟糕透了”

雖然已經是25歲&#xff0c;但是對小學的一篇課文依然記憶尤新&#xff0c;《“精彩極了”和“糟糕透了”》。 課文正文 記得七八歲的時候&#xff0c;我寫了第一首詩。母親一念完那首詩&#xff0c;眼睛亮亮的&#xff0c;興奮地嚷著&#xff1a;“巴迪&#xff0c;真是你寫的…

python中print的用法_Python中print函數簡單使用總結

Python中print函數簡單使用總結 print函數是Python的入門&#xff0c;每一個學習python的人都繞不開這個函數&#xff0c;下面介紹一下這個函數的用法。 打開電腦&#xff0c;選擇python軟件&#xff0c;下面選擇python 3.7為例進行介紹&#xff0c;點擊python 3.7&#xff0c;…

STM32F1筆記(十)PWM

PWM&#xff1a;Pulse Width Modulation&#xff0c;脈沖寬度調制。是利用微處理器的數字輸出來對模擬電路進行控制的一種非常有效的技術。簡單來說就是對脈沖寬度的控制。 在《STM32中文參考手冊》里可以看到 占空比&#xff1a;占空比是指在一個脈沖循環內&#xff0c;通電時…

從GlassFish 3.x擴展到WebLogic 12c Server

Oracle針對GlassFish服務器的策略的主要目標之一是“與Fusion Middleware and Products集成”&#xff08;來源&#xff1a; Community Roadmap&#xff0c;2010年5月 &#xff09;。 在今年早些時候&#xff0c;您聽到了很多關于兩臺服務器合而為一的恐懼和謠言。 看到這兩種產…

移動互聯網時代:如何讓女孩愛上你在一分鐘內?

部分《移動互聯網時代&#xff1a;讓女孩愛上你在一分鐘內》其實我只是做原來的盲目思想有移動互聯網的自主知識產權&#xff0c;他沒有詳細說明如何真正讓女孩愛上你在一分鐘內&#xff1f;在真實生活中&#xff0c;預期也沒有那么簡單&#xff0c;易于&#xff0c;畢竟&#…

hashset去重原理_基于simhash的文本去重原理

互聯網網頁存在著大量重復內容&#xff0c;必須有一套高效的去重算法&#xff0c;否則爬蟲將做非常多的無用功&#xff0c;工作時效性無法得到保證&#xff0c;更重要的是用戶體驗也不好。業界關于文本指紋去重的算法眾多&#xff0c;如 k-shingle 算法、google 提出的simhash …

解決express video 手機無法播放的問題

http://stackoverflow.com/questions/24976123/streaming-a-video-file-to-an-html5-video-player-with-node-js-so-that-the-video-c 項目地址 https://github.com/shenggen1987/mp4-demo express index.jade extends layoutblock contenth1 titlep Welcome to #{title}vid…

STM32F1筆記(十一)ADC

查看《STM32中文參考手冊》里ADC的介紹和特性 STM32的ADC最大轉換速率為1Mhz&#xff0c;即1us&#xff0c;在ADCCLK14M&#xff0c;采樣周期為1.5個ADC時鐘下得到。當ADC的時鐘超過14M時&#xff0c;將導致結果準確度下降。 規則通道相當于正常運行的程序。注入通道就相當于中…

使用JPA和Spring 3.1進行事務配置

1.概述 本教程將討論配置Spring Transactions &#xff0c;使用Transactional批注和常見陷阱的正確方法 。 要更深入地討論核心持久性配置&#xff0c;請查看Spring with JPA教程 。 有兩種不同的配置事務的方法– 批注和AOP –每種都有自己的優勢–我們將在這里討論更常見的…

java epoll select_字節跳動高頻面試題,操作系統/算法/Java等。

字節跳動# Java▲ 20 Java 中垃圾回收機制中如何判斷對象需要回收&#xff1f;常見的 GC 回收算法有哪些&#xff1f;▲ 18 synchronized 關鍵字底層是如何實現的&#xff1f;它與 Lock 相比優缺點分別是什么&#xff1f;▲ 17 hashmap 和 hashtable 的區別是什么&#xff1f;▲…

Xamarin Android項目運行失敗

Xamarin Android項目運行失敗 錯誤信息&#xff1a;Build Failed: MonoDroid does not support running the previous version. Please ensure your solution builds before running or debugging it.這是由于由于項目生成失敗&#xff0c;并找不到以前編譯的結果。這時&#…

STM32F1筆記(十二)DAC

先看《STM32中文參考手冊》中DAC的介紹 引腳的定義與ADC類似 這里需要留意手冊提供的注意&#xff0c;DAC應該是輸出&#xff0c;但是GPIO初始化配置時卻要設置為模擬輸入。 DAC配置示例 void DAC_Init(void) {GPIO_InitTypeDef GPIO_InitStructure;DAC_InitTypeDef DAC_Init…

有關為舊版代碼創建存根的更多信息–測試技術7

在上一個博客中 &#xff0c;我談到了如何處理行為不佳的不可測試的 &#xff08;1&#xff09; SitePropertiesManager 類&#xff0c;以及如何通過提取接口來創建存根。 但是&#xff0c;如果由于舊類的源代碼已被鎖定在第三方JAR文件中而無法訪問它&#xff0c;會發生什么情…

python動態時鐘代碼_python繪制動態時鐘

桌面時鐘項目描述 1、使用turtle庫繪制時鐘外形及表針&#xff1b; 2、使用datetime獲取系統時間&#xff1b; 3、時鐘動態顯示 turtle庫基本命令 1、turtle.setup()函數&#xff1a;用于啟動一個圖形窗口&#xff0c;它有四個參數turtle.setup(width, height, startx, starty)…