簡體   English   中英

如何使用JAXB將列表編組到XML文件?

[英]How to marshall a List to an XML file with JAXB?

尋找使用XML 編組 和解組對象。

這對於一個客戶來說很好,它創建為:

thufir@dur:~/jaxb$ 
thufir@dur:~/jaxb$ ls
jaxbexample.xml
thufir@dur:~/jaxb$ 
thufir@dur:~/jaxb$ cat jaxbexample.xml 
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="0">
    <age>44</age>
    <name>mkyong</name>
</customer>
thufir@dur:~/jaxb$ 

如何創建“ Customer對象List並將其寫入xml文件?

package helloWorldSaxon;

import java.io.File;
import java.util.List;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.Result;
import javax.xml.transform.dom.DOMResult;

//https://stackoverflow.com/q/17059227/262852

public class JaxBExample {

    private static final Logger LOG = Logger.getLogger(JaxBExample.class.getName());
    private String pathToFile = "/home/thufir/jaxb/jaxbexample.xml";
    private int id = 0;

    public JaxBExample() {
    }

    public Customer readCustomerFromFile() throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Customer.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File(pathToFile);
        Customer customer = (Customer) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "/tmp/bla-bla.xsd"); //???
        Result result = new DOMResult();  //what to do with result?? nothing?
        marshaller.marshal(customer, result);
        return customer;
    }

    public Customer dummyCustomer() throws Exception {
        Customer customer = new Customer();
        customer.setId(id);
        customer.setName("mkyong");
        customer.setAge((int) (Math.random() * 100));
        id++;
        return customer;
    }

    public void writeCustomersTofile(List<Customer> customers) {
        //new file, overwrite old file.
        //write a collection to the file
        //so that each customer can then be read in.
        //import to basex
    }

    public void writeCustomerToFile(Customer customer) throws Exception {
        File file = new File(pathToFile);
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(customer, file);
    }

}

BaseXCustomer數據庫的上下文中:

thufir@dur:~/jaxb$ 
thufir@dur:~/jaxb$ basex
[warning] /usr/bin/basex: Unable to locate /usr/share/java/jing.jar in /usr/share/java
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
> 
> CREATE DB customers jaxbexample.xml
Database 'customers' created in 367.3 ms.
> 
> XQUERY /
<customer id="0">
  <age>44</age>
  <name>mkyong</name>
</customer>
Query executed in 213.83 ms.
> 
> exit
Enjoy life.
thufir@dur:~/jaxb$ 

但是,目前暫時不要使用BaseX API,為此請嚴格使用JAXB

只是想構建一個格式正確多個Customer對象的文件。 (我認為這甚至沒有必要。)

到目前為止,我發現了 “最簡單”的解決方案:

package com.danibuiza.jaxb.ultimate.marshal;

import java.io.File;
import java.time.LocalDate;

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

import com.danibuiza.jaxb.ultimate.business.Countries;
import com.danibuiza.jaxb.ultimate.business.Country;



/**
 * Simple example of usage of jaxb marshaling functionalities showing how to manage lists
 * 
 * @author dgutierrez-diez
 */
public class JaxBExampleList
{

    public static void main( String[] args )
    {
        try
        {

            /* init a list with a couple of countries to marshal */
            Country spain = new Country();
            spain.setName( "Spain" );
            spain.setCapital( "Madrid" );
            spain.setContinent( "Europe" );

            spain.setFoundation( LocalDate.of( 1469, 10, 19 ) );

            Country usa = new Country();
            usa.setName( "USA" );
            usa.setCapital( "Washington" );
            usa.setContinent( "America" );


            usa.setFoundation( LocalDate.of( 1776, 7, 4 ) );

            Countries countries = new Countries();
            countries.add( spain );
            countries.add( usa );

            /* init jaxb marshaler */
            JAXBContext jaxbContext = JAXBContext.newInstance( Countries.class );
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            /* set this flag to true to format the output */
            jaxbMarshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );

            /* marshaling of java objects in xml (output to file and standard output) */
            jaxbMarshaller.marshal( countries, new File( "list_countries.xml" ) );
            jaxbMarshaller.marshal( countries, System.out );

        }
        catch( JAXBException e )
        {
            e.printStackTrace();
        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM