Python XML + Java XML 互操作性
我需要一个可以将 python 对象编组为 XML(让它成为一个文件)的 pythonic 库的推荐。 我需要稍后能够使用 Java (JAXB) 读取该 XML 并将其解组。 我知道 JAXB 有一些问题,导致它无法与 .NET XML 库很好地配合,因此推荐一些实际有效的东西会很棒。
I need a recommendation for a pythonic library that can marshall python objects to XML(let it be a file).
I need to be able read that XML later on with Java (JAXB) and unmarshall it.
I know JAXB has some issues that makes it not play nice with .NET XML libraries so a recommendation on something that actually works would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 Ignacio 所说,XML 就是 XML。在 python 方面,我建议使用 lxml,除非您有其他库可以更好地满足的更具体的需求。如果您仅限于标准库,请查看
ElementTree
或cElementTree
,它们也非常出色,并且启发了lxml(并且在功能上大多等同于)。 etree
。编辑:仔细观察,您似乎不仅仅是在寻找 XML,而是在寻找对象的 XML 表示形式。为此,请查看
lxml.objectify
或 Amara。我还没有尝试使用它们来实现与 Java 的互操作性,但它们值得一试。如果您只是在寻找一种进行数据交换的方法,您也可以尝试自定义 JSON 对象。As Ignacio says, XML is XML. On the python side, I recommend using
lxml
, unless you have more specific needs that are better met by another library. If you are restricted to the standard library, look atElementTree
orcElementTree
, which are also excellent, and which inspired (and are functionally mostly equivalent to)lxml.etree
.Edit: On closer look, it seems you are not just looking for XML, but for XML representations of objects. For this, check out
lxml.objectify
, or Amara. I haven't tried using them for interoperability with Java, but they're worth a try. If you're just looking for a way to do data exchange, you might also try custom JSON objects.您可能遇到的问题是您用来封送对象的 Python 和 Java 库的默认格式。任何像样的库,包括 JAXB 允许自定义
您需要决定 XML 的结构,然后使用库功能来使用和发出 XML 结构,而不是依赖默认值,默认值在不同编程语言的不同库中永远不会相同。
The issue your are probably having is the default format of the Python and Java libraries you are using to marshal your objects. Any decent libraries including JAXB allows customisation of how objects should be represented in XML.
You need to decide what the structure of your XML should be then use your libraries features to consume and emit your XML structure rather than relying on the defaults which would never be the same across different libraries in different programming languages.