栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

用JAXB读取Xml文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用JAXB读取Xml文件

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>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/596050.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号