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

xml对象映射

xml对象映射_将对象映射到多个XML模式–天气示例相关推荐

  1. 将对象映射到多个XML模式–天气示例

    我已经在EclipseLink JAXB(MOXy)的@XmlPath和外部绑定文件扩展中撰写了以前的文章. 在本文中,我将通过将单个对象模型映射到两个不同的XML模式来演示这些扩展的功能. 为了使示 ...

  2. hibernate关联映射_具有关联映射的Hibernate Composite ID

    hibernate关联映射 最近,我们面临着带有复合id字段的Hibernate关联映射的棘手情况. 我们需要与一对一和多对一进行双向关联.我们的拖曳表是" REPORT"和&qu ...

  3. python中类似对象吗_确定对象是否为Python中类似字节的对象的正确方法是什么?...

    除非您知道我们不了解的内容,否则此代码是不正确的: if isinstance(data, bytes): data = data.decode() 您(似乎)不知道27007050676610010 ...

  4. 使用枚举映射_用EnumMaps映射枚举键

    使用枚举映射 这是一种在JDK中存在很长时间的类型,当我们要定义以枚举类型作为键的映射时,这种类型会派上用场: EnumMap是一种特殊的Map . 我们将为给定的枚举创建一个映射: public e ...

  5. xbox手柄映射_如何重新映射您的Xbox One控制器的按钮

    xbox手柄映射 Microsoft's Xbox One allows you to remap the buttons on its controller. This feature was or ...

  6. Java找对象笑话_找对象相亲的笑话几则,爱情笑话

    原标题:找对象相亲的笑话几则,爱情笑话 找对象相亲的笑话几则,爱情笑话 今天小编一来就听到关系比较好的同事妹纸在说昨天相亲遇到的奇葩.听完以后小编只能感慨,这其实是个相亲笑话吧?妹纸的相亲对象居然带着 ...

  7. Java找对象笑话_找对象相亲的笑话7则,爱情笑话

    1.选 择姑娘和小伙子经婚姻介绍所安排,在公园里见了面.两人谈了没一会儿,姑娘便起身告 辞.小伙子对姑娘很中意,见她要走,心里很急,连忙追问原因. 姑娘:"你虽然相貌堂堂,可是腹中空空.&q ...

  8. 在mysql中数据库对象包括_数据库对象包括哪六个?

    数据库对象包括:用户(对数据库有权限访问的人).视图(显示用户需要的数据项).索引(给用户提供快速访问数据的途径).触发器(用户定义的SQL事务命令集合).序列(提供了唯一数值的顺序表).图表(数据库 ...

  9. 同时介绍两个对象怎么办_“相亲对象好着急,认识第一天就干出这事?”哈哈哈哈哈我该怎么办|哈哈哈哈哈|相亲|情侣|借钱|电子厂...

    "相亲对象好着急,认识第一天就干出这事?"哈哈哈哈哈我该怎么办 家人一直就觉得我老大不小了,该找个结婚对象好好过日子了.所以这段时间一直给我介绍各种各样的相亲对象,相亲也是大同小异 ...

最新文章

  1. 漫画:程序教你玩转股票
  2. 【iCore4 双核心板_FPGA】例程七:状态机实验——状态机使用
  3. Handler延迟事件使用
  4. 表达式树练习实践:入门基础
  5. Maven国内镜像 Maven阿里云镜像
  6. [Nikon D80]樱花盛开的校园
  7. aixs1 生成java代码_通过axis1.4 来生成java客户端代码
  8. UPC 2019年第二阶段我要变强个人训练赛第六场
  9. ASP.NET 2.0之HtmlInputFile控件使用小结
  10. Android 存储学习之SQLite数据库的基本操作 (使用API操作数据库)
  11. sp3 win xp 符号表_Windows XP with SP3 各版本全搞定(附序列号)
  12. 软件测试项目实战经验附视频以及源码【商城项目,app项目,电商项目,银行项目,医药项目,金融项目】
  13. excel转置怎么操作_PDF转excel怎么操作?这个方法一定要熟知!
  14. Redis 6.2的过期删除策略源码分析(定期删除)
  15. 【Java基础总结】类加载顺序,new关键字,访问权限修饰符与方法重载等【二】
  16. redis安装及部署模式
  17. 怎么把歌曲导入备忘录里
  18. 猛犸Winform分页控件
  19. 【ironic】ironic介绍与原理
  20. 我的前半生:多情剑客无情剑

热门文章

  1. 调用反射类的指定方法
  2. 多线程三种同步方式(模拟银行取款)
  3. SpringAOP的SchemaBase方式
  4. 2019蓝桥杯省赛---java---A---8(修改数组)
  5. 尚硅谷2020最新版SpringCloud(H版alibaba)框架开发教程全套完整版从入门到精通
  6. php 错误提示开启,php开启与关闭错误提示,php开启错误提示_PHP教程
  7. 2015c语言9月答案,2015年9月计算机二级C语言预测题答案
  8. spring(4)面向切面的Spring(AOP)
  9. java集合框架——接口图+类图+遗留类图
  10. jdk入门_JDK 9 REPL:入门