将对象映射到多个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.mzph.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)…