1

POJO インスタンスを DB に保存せずに XML 表現に変換し、DOM4J モードで (および XML から POJO に) 再度ロードすることは可能ですか?

4

3 に答える 3

4

私はまだこれを使用していませんが、DOM4J には、POJO を XML (DOM4J) に変換するために使用できる JAXB 統合があるようです。

アップデート

DOM4J は、DocumentResultを実装するクラスも提供しますjavax.xml.transform.Result。JAXB を使用してこのクラスにマーシャリングし、結果の DOM4JDocumentオブジェクトを操作できます。

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import org.dom4j.Document;
import org.dom4j.io.DocumentResult;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Create the JAXBContext
        JAXBContext jc = JAXBContext.newInstance(Customer.class);

        // Create the POJO
        Customer customer = new Customer();
        customer.setName("Jane Doe");

        // Marshal the POJO to a DOM4J DocumentResult
        Marshaller marshaller = jc.createMarshaller();
        DocumentResult dr = new DocumentResult();
        marshaller.marshal(customer, dr);

        // Manipulate the resulting DOM4J Document object
        Document document = dr.getDocument();
        document.getRootElement().addAttribute("foo", "bar");

        // Output the result
        System.out.println(document.asXML());
    }

}
于 2011-08-03T15:49:58.657 に答える
1

JDKの一部であるJAXB(パッケージjavax.xml.bind)以外は何も必要ありません(JDK6から始まると思います)。初心者のためにJAXBContextと@XmlRootElementアノテーションを調べてください

于 2011-08-03T15:55:06.093 に答える
0

多くの XML シリアライゼーション ライブラリがあります。

私自身、XStream の大ファンです。使い方は非常に簡単で、.xsd は必要ありません。

于 2011-08-03T16:40:10.220 に答える