JAXB

Материал из Home Wiki
Перейти к навигации Перейти к поиску

Категория:Работа

Создание классов JAXB из XSD

http://www.javawebtutor.com/articles/jaxb/jaxb_java_class_from_xsd.php

Обработка большого XML с использованием JAXB

https://stackoverflow.com/questions/1134189/can-jaxb-parse-large-xml-files-in-chunks

package x;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import static javax.xml.stream.XMLStreamConstants.*;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import org.hibernate.result.Outputs;
/* import autogenerated classes here */
/* VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV */
import x.RealtyFeed;
import x.RealtyFeed.Offer;
import x.RealtyFeed.Offer.Location;
/* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */

public class TestXml implements AutoCloseable {
    private XMLStreamReader reader;
    private Unmarshaller unmarshaller;
    private Marshaller marshaller;

    private void showOffer (Offer offer) throws JAXBException, IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        RealtyFeed root = new RealtyFeed();
        root.getOffer().add(offer);
        marshaller.marshal(root, os);
        System.out.write(os.toByteArray());
    }

    public static void main(String[] args) throws JAXBException, XMLStreamException, FactoryConfigurationError, IOException {
        try(InputStream stream = new FileInputStream("/path/to/big.xml");
                TestXml x = new TestXml(stream)) {
            long count = 0;
            RealtyFeed.Offer offer = null;
            while(x.hasNext()) {
                offer = x.next();
                if (offer != null) {
                    boolean sale = false;
                    for(JAXBElement<?> elem : offer.getTypeOrPropertyTypeOrCategory()) {
                        String nameLocalPart = elem.getName().getLocalPart();

                        if ("type".equals(nameLocalPart)) {
                            saveAndCount(type, (String)elem.getValue());
                            if ("продажа".equals((String)elem.getValue())) {
                                sale = true;
                            }
                        }
                    }
                    if (sale) {
                        x.showOffer(offer);
                    }
                    count ++;
                    if (count % 1000 == 0) { 
                        System.out.print("\rCount: " + count);
                    }
                }
            }
            System.out.println("\r\nTotal count: " + count);
        }
    }

    public TestXml(InputStream stream) throws XMLStreamException, JAXBException {
        marshaller = JAXBContext.newInstance(RealtyFeed.class).createMarshaller();
        unmarshaller = JAXBContext.newInstance(RealtyFeed.class).createUnmarshaller();
        reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
        /* ignore headers */
        skipElements(START_DOCUMENT, DTD);
        /* ignore root element */
        reader.nextTag();
        /* if there's no tag, ignore root element's end */
        skipElements(END_ELEMENT);
    }

    public RealtyFeed.Offer next() throws XMLStreamException, JAXBException {
        if (!hasNext())
            throw new NoSuchElementException();

        RealtyFeed.Offer value = unmarshaller.unmarshal(reader, RealtyFeed.Offer.class).getValue();

        skipElements(END_ELEMENT);
        return value;
    }

    public boolean hasNext() throws XMLStreamException {
        return reader.hasNext();
    }

    public void close() throws XMLStreamException {
        reader.close();
    }

    void skipElements(Integer... elements) throws XMLStreamException {
        int eventType = reader.getEventType();
        List<Integer> types = Arrays.asList(elements);
        while (types.contains(eventType)) {
            eventType = reader.next();
        }
    }
}