Saving Java Object Graphs as XML file

前端 未结 15 2550
耶瑟儿~
耶瑟儿~ 2021-02-07 12:13

What\'s the simplest-to-use techonlogy available to save an arbitrary Java object graph as an XML file (and to be able to rehydrate the objects later)?

15条回答
  •  难免孤独
    2021-02-07 13:08

    Use java.beans.XMLEncoder. Its API is very simple (actually a little too simple; it'd be nice to wire it to a SAX ContentHandler), but it works on many graphs out of the box, and it's easy to create your own persistence delegate for any odd-ball classes you might encounter.

    • The syntax used by XMLDecoder allows you to invoke any method, instance or static, including constructors, so it's extremely flexible.
    • Other encoders name elements and attributes after class and field names, so there's no fixed schema for the result. The XMLEncoder's XML follows a simple DTD and can easily be validated or transformed, even when you've never seen the types it uses.
    • You can assign objects an identifier, and reference them throughout the graph.
    • You can refer to constants defined in classes or interfaces.

    And, it's built into Java SE, so you don't need to ship an extra library.

提交回复
热议问题