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)
您需要确保使用
@XmlRootElement或将类与XML文档的根元素相关联
@XmlElementDecl(请参阅:http : //blog.bdoughan.com/2012/07/jaxb-and-root-
elements.html)。或者,您可以使用带
Class参数的解组方法之一来告诉JAXB您要解组的对象类型。
域模型(配置)
我建议您使用如下域类,从中可以获取两个
Property对象列表。
import java.util.*;import javax.xml.bind.annotation.*;@XmlRootElementpublic 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; }}演示版
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 /输出
<?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>



