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?
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 logProperties = new ArrayList();
private List envProperties = new ArrayList();
@XmlElementWrapper(name="log")
@XmlElement(name="property")
public List getLogProperties() {
return logProperties;
}
@XmlElementWrapper(name="env")
@XmlElement(name="property")
public List 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