Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read Xml file with JAXB

Tags:

java

xml

jaxb

I want to read a xml file (like below) but I get an Execption. Could you please help me how can I fix this problem?

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation=
"file:///C:/Documents%20and%20Settings/mojalal/Desktop/FirstXSD.xml">
<log>
    <property key="firstKey" value="firstValue"></property>
    <property key="secoundKey" value="secoundKey"></property>
    <property key="thirdKey" value="thirdValue"></property>  
</log>

<env>
    <property key="firstenv" value="fo"></property>
    <property key="123" value="333"></property> 
</env>
</config>

and this is my code that I want to read xml file:

    public class ReadXMLFilewithJAXB {
private static List<Property> customer;

@SuppressWarnings("unchecked")
public static void main(String[] args) {

 try {

    File file = new File("c:\\FirstXML.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Log.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    customer = (List<Property>) jaxbUnmarshaller.unmarshal(file);
 } catch (JAXBException e) {
    e.printStackTrace();
  }

}

}

Finally this is the Exception that I get:

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"config"). Expected elements are (none)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:631)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:236)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:231)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:105)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1038)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:467)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:448)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:137)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:400)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:626)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3103)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:922)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:200)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:173)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:142)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:151)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:169)
    at firstExample.ReadXMLFilewithJAXB.main(ReadXMLFilewithJAXB.java:21)

Env POJO Class:

public class Env {
    List<Property> properties2;


    public Env() {
    }


    public Env(List<Property> properties2) {
        super();
        this.properties2 = properties2;
    }


    public List<Property> getProperties2() {
        return properties2;
    }

    public void setProperties2(List<Property> properties2) {
        this.properties2 = properties2;
    }

LOg POJO Class:

@XmlRootElement
public class Log {
    List<Property> properties=new ArrayList<Property>();;

    public Log(){

    }

    public List<Property> getProperties() {
        return properties;
    }

    public void setProperties(List<Property> properties) {
        this.properties = properties;
    }
like image 354
Reza Avatar asked Jun 12 '13 06:06

Reza


People also ask

How do I read XML files?

XML files can be opened in a browser like IE or Chrome, with any text editor like Notepad or MS-Word. Even Excel can be used to open XML files.

How do I read an XML string in Java?

You can parse the XML file using XPath expression, you can do XSL transformation, XSD schema validation and you can even parse whole XML file as String in just a couple of lines of code.

Is JAXB deprecated?

JAXB is one of the APIs in the Jakarta EE platform (formerly Java EE), part of the Java Web Services Development Pack (JWSDP), and one of the foundations for WSIT. It was also part of the Java SE platform (in version Java SE 6-10). As of Java SE 11, JAXB was removed.

How do you Unmarshal XML string to Java object using JAXB?

To unmarshal an xml string into a JAXB object, you will need to create an Unmarshaller from the JAXBContext, then call the unmarshal() method with a source/reader and the expected root object.


1 Answers

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"config"). Expected elements are (none)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:631)

You need to ensure that you associate a class with the root element of the XML document using @XmlRootElement or @XmlElementDecl (see: http://blog.bdoughan.com/2012/07/jaxb-and-root-elements.html). Alternatively you can use one of the unmarshal methods that take a Class parameter to tell JAXB what type of object you are unmarshalling.


Domain Model (Config)

I would recommend having a domain class like the following from which you could obtain the two lists of Property objects.

import java.util.*;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class Config {

    private List<Property> logProperties = new ArrayList<Property>();
    private List<Property> envProperties = new ArrayList<Property>();

    @XmlElementWrapper(name="log")
    @XmlElement(name="property")
    public List<Property> getLogProperties() {
        return logProperties;
    }

    @XmlElementWrapper(name="env")
    @XmlElement(name="property")
    public List<Property> getEnvProperties() {
        return envProperties;
    }

}

Demo

import java.io.File;
import javax.xml.bind.*;

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum17059227/input.xml");
        Config config = (Config) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "file:///C:/Documents%20and%20Settings/mojalal/Desktop/FirstXSD.xml");
        marshaller.marshal(config, System.out);
    }

}

input.xml/Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///C:/Documents%20and%20Settings/mojalal/Desktop/FirstXSD.xml">
    <env>
        <property key="firstenv" value="fo"/>
        <property key="123" value="333"/>
    </env>
    <log>
        <property key="firstKey" value="firstValue"/>
        <property key="secoundKey" value="secoundKey"/>
        <property key="thirdKey" value="thirdValue"/>
    </log>
</config>
like image 60
bdoughan Avatar answered Oct 19 '22 10:10

bdoughan