Read XML file

0

I have the following program:

package exercici3;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
 *
 * @author Montse
 */
@XmlRootElement
@XmlType(propOrder ={"autor", "nom", "editorial","isbn", "llibre"})    
public class Llibreria extends MarshalClass{

    private String autor;
    private String nom;
    private String editorial;
    private String isbn;
    private ArrayList<Llibre> llibre=new ArrayList<Llibre>();

    @XmlElement
    public String getAutor(){return autor;}
    public void setAutor (String autor){this.autor =autor;}  
    @XmlElement
    public String getNom(){return nom;}
    public void setNom (String nom){this.nom =nom;}
    @XmlElement
    public String getEditorial(){return editorial;}
    public void setEditorial (String editorial){this.editorial =editorial;}
    @XmlElement
    public String getIsbn(){return isbn;}
    public void setIsbn (String isbn){this.isbn =isbn;} 
    @XmlElement
    public ArrayList <Llibre> getLlibre() { return llibre;}
    public void setLlibre(ArrayList<Llibre> llibre){ this.llibre= llibre;}

}    






package exercici3;

import java.util.ArrayList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Montse
 */
@XmlRootElement(name="llibr")

class Llibre extends MarshalClass {

    private String autor;
    private String nom;
    private String editorial;
    private String isbn;
        private ArrayList<Llibre> llibre=new ArrayList<Llibre>();

    @XmlElement
    public String getAutor(){ return autor;}
    public void setAutor (String autor){ this.autor = autor;}

    @XmlElement
    public String getNom(){ return nom;}
    public void setNom (String nom){ this.nom = nom;}

    @XmlElement
    public String getEditorial(){ return editorial;}
    public void setEditorial (String editorial){ this.editorial = editorial;}

    @XmlElement
    public String getIsbn(){ return isbn;}
    public void setIsbn (String isbn){ this.isbn = isbn;}


     @XmlElement
    public ArrayList <Llibre> getLlibre() { return llibre;}
    public void setLlibre(ArrayList<Llibre> llibre){ this.llibre= llibre;}
    }




package exercici3;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

/**
 *
 * @author Montse
 */
public class MarshalClass {

    public void generateXML (String nameFile) {

        try{
            File file = new File (nameFile);
            JAXBContext jc = JAXBContext.newInstance(this.getClass());
            Marshaller jaxbMarshaller = jc.createMarshaller();

            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT , true);

            jaxbMarshaller.marshal(this, new FileWriter(nameFile, true));

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

}



package exercici3;

import java.util.ArrayList;

/**
 *
 * @author Montse
 */
public class Entrada {

    public static void main(String[]args){

        EscriureLlibreria();

    }

    private static void EscriureLlibreria() {

        Llibreria cc = new Llibreria();
        cc.setAutor("Xavier");
        cc.setNom("Nosotros dos");
        cc.setEditorial("Columna");
        cc.setIsbn("9788-4664-222-84");

        ArrayList<Llibre> alCU = new ArrayList<>();
      int init = 2000;
              for (int i =1; i<1;i++){
        Llibre cu = new Llibre();
        cu.setAutor(""+i);
        cu.setNom(""+i);
        cu.setEditorial(""+i);
        cu.setIsbn(""+i);
        alCU.add(cu);       
    }
                cc.setLlibre(alCU);
                cc.generateXML("llibres.xml");


    }

}

I want the file I created called llibres.xml to show me on the screen ... and I've done the following:

package exercici3;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
/**
 *
 * @author Montse
 */
public class Sortida {
    public static void main (String[] args) {


        try{
            JAXBContext context = JAXBContext.newInstance(Llibreria.class);
            Unmarshaller ums = context.createUnmarshaller();
            Llibre llibreria = (Llibre) ums.unmarshal(new File("llibres.xml"));
            for (Llibre llib: llibreria.getLlibre()){
                System.out.println("Nom" +llib.getNom());
                System.out.println("Autor:"+llib.getAutor());
                System.out.println("ISBN:"+llib.getIsbn());
                System.out.println("Editorial"+llib.getEditorial());
            }
        }catch (JAXBException e){
            e.printStackTrace();
        }

    }



}

I get this error:

javax.xml.bind.UnmarshalException
 - with linked exception:
[org.xml.sax.SAXParseException; systemId: file:/C:/Users/Montse/Documents/NetBeansProjects/Exercici3/llibres.xml; lineNumber: 8; columnNumber: 6; El destino de la instrucción de procesamiento que coincide con "[xX][mM][lL]" no está permitido.]
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:335)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:563)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:249)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:162)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:171)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:189)
    at exercici3.Sortida.main(Sortida.java:18)
Caused by: org.xml.sax.SAXParseException; systemId: file:/C:/Users/Montse/Documents/NetBeansProjects/Exercici3/llibres.xml; lineNumber: 8; columnNumber: 6; El destino de la instrucción de procesamiento que coincide con "[xX][mM][lL]" no está permitido.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:400)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327)
    at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1472)
    at com.sun.org.apache.xerces.internal.impl.XMLScanner.scanPIData(XMLScanner.java:746)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanPIData(XMLDocumentFragmentScannerImpl.java:1014)
    at com.sun.org.apache.xerces.internal.impl.XMLScanner.scanPI(XMLScanner.java:714)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$TrailingMiscDriver.next(XMLDocumentScannerImpl.java:1413)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:841)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:770)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:243)
    ... 6 more

What am I wrong?

thanks!

EDITO

The error occurs because the file creates it several times. How can I modify it to create it only once?

Then now the error you give me:

Exception in thread "main" java.lang.ClassCastException: exercici3.Llibreria cannot be cast to exercici3.Llibre
    at exercici3.Sortida.main(Sortida.java:18)
C:\Users\Montse\AppData\Local\NetBeans\Cache.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
    
asked by Montse Mkd 28.09.2017 в 12:39
source

2 answers

2

in the end I think you can use this form

public class Sortida {

public static void main(String[] args) {

    try {
        JAXBContext context = JAXBContext.newInstance(Llibreria.class);
        Unmarshaller ums = context.createUnmarshaller();
        JAXBElement<Llibre> rootElementCast = ums.unmarshal(new StreamSource(new File("llibres.xml")), Llibre.class);
        Llibre llibreria = rootElementCast.getValue();
        //for (Llibre llib : llibreria.getLlibre()) {
            System.out.println("Nom" + llibreria.getNom());
            System.out.println("Autor:" + llibreria.getAutor());
            System.out.println("ISBN:" + llibreria.getIsbn());
            System.out.println("Editorial" + llibreria.getEditorial());
            //des-n
            System.out.println("libre" + llibreria.getLlibre());
        //}
    } catch (JAXBException e) {
        e.printStackTrace();
    }

}

according to the documentation here

I've been testing it for myself and although Libre has the annotation XmlRootElement in the documentation they specify another way to do it and it worked for me.

    
answered by 28.09.2017 / 14:57
source
1

I've been looking for and the error ( in the English version )

  

The processing instruction target matching "[xX] [mM] [lL]" is not   allowed

It means that the start of the file is not exactly <?xml ...> . These characters can only be in the first line of the file and it is certainly not allowed to have a space in front of them (it depends on the rigor of the parser used)

    
answered by 28.09.2017 в 15:07