简单的、结构化类型的 XML 数据绑定(无需代码生成或反射) [英] Simple, structurally typed XML data binding (without code generation or reflection)

查看:21
本文介绍了简单的、结构化类型的 XML 数据绑定(无需代码生成或反射)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个 Java 库,它允许我将 XML 编组到 Java 对象树,反之亦然.有很多库可以让我将 XML 绑定到由某些代码生成工具生成的 JavaBeans,但是,我不需要这些库(JAXB、JiBX、Castor 等).

I'm looking for a Java library that would allow me to marshal XML to a Java object tree, and vice versa. There are plenty of libraries that would allow me to bind XML to JavaBeans generated by some code generation tool, however, I don't need those (JAXB, JiBX, Castor and so on).

我需要的是一个工具,它可以使用一个模式文件和一个 xml 文件,然后返回 Maps、Lists 和 Object<的组合/code>s 的方式类似于 Jackson 的简单数据绑定(当然,在可能的情况下).Jackson 适用于 JSON,而不是 XML;并且它缺乏考虑模式文件的能力(因为 JSON 模式目前太不成熟).

What I need is a tool which would consume a schema file and an xml file and then return a combination of Maps, Lists and Objects in a manner similar to Jackson's simple data binding (when it is possible, of course). Jackson is intended for JSON, not for XML; and it lacks the ability to take a schema file in account (because JSON Schema is too immature at the moment).

我可以调整一些现有的工具来解决我的问题,还是应该使用 DOM 和 XSOM 推出我自己的解决方案?

Can I adapt some existing tools to solve my problem, or should I roll out my own solution with DOM and XSOM?

推荐答案

MOXy 的动态 JAXB

MOXy 提供动态 JAXB 实现.您可以从 XML 模式引导,而不是静态类,您可以使用通用的 get/set 方法与 DynamicEntity 的实例交互:

MOXy offers a dynamic JAXB implementation. You can bootstrap from an XML schema and instead of static classes you can interact with instances of DynamicEntity with generic get/set methods:

FileInputStream xsd = new FileInputStream("src/example/customer.xsd");
DynamicJAXBContext jaxbContext = 
    DynamicJAXBContextFactory.createContextFromXSD(xsd, null, null, null);

FileInputStream xmlInputStream = new FileInputStream("src/example/dynamic/customer.xml");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
DynamicEntity customer = (DynamicEntity) unmarshaller.unmarshal(xmlInputStream);

System.out.println(customer.<String>get("name"));

有关更多信息,请参阅:

For more information see:

服务数据对象 (SDO)

您也可以为此使用服务数据对象 (JSR-235).

You could also use Service Data Objects for this (JSR-235).

FileReader xsd = new FileReader("customer.xsd");
XSDHelper.INSTANCE.define(xsd, null);

FileReader xml = new FileReader("input.xml");
XMLDocument doc = XMLHelper.INSTANCE.load(xml, null, null);

DataObject customerDO = doc.getRootObject();
int id = customerDO.getInt("id");
DataObject addressDO = customerDO.getDataObject("contact-info/address");

有关更多信息,请参阅:

For more information see:

这篇关于简单的、结构化类型的 XML 数据绑定(无需代码生成或反射)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆