zhkchi 2011-07-29 13:37
浏览 611
已采纳

如何利用JAXBContext Unmarshaller读取xml里面的汉字?

JAXBContext jc = JAXBContext.newInstance(A.class);
Unmarshaller un = jc.createUnmarshaller();
un.setSchema(getSchema());

如果我的xml文件里面包含了汉字,那么就会产生, 错误, 有没有什么办法可以做到可以在xml写汉字,读取不出错呢?

  • 写回答

1条回答 默认 最新

  • myali88 2011-08-05 23:53
    关注

    是不是你自己xml文件编码问题,我这样不会有问题:
    [code="java"]

    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.Writer;
    import java.util.Date;

    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.Unmarshaller;

    import com.ulinkwo.example.Event;

    public class XmlMashaller {

    private static final String XML = "event.xml";
    
    public static void main(String[] args) throws Exception {
        marshall();
        unmarshall();
    }
    
    private static void marshall() throws Exception {
        Event event = new Event();
        event.setDate(new Date());
        event.setName("开机");
    
        JAXBContext context = JAXBContext.newInstance(Event.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.marshal(event, System.out);
    
        Writer w = null;
        try {
            w = new FileWriter(XML);
            m.marshal(event, w);
        } finally {
            try {
                w.close();
            } catch (Exception e) {
            }
        }
    }
    
    private static void unmarshall() throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Event.class);
        Unmarshaller un = jc.createUnmarshaller();
        Event event = (Event) un.unmarshal(new FileReader(XML));
    
        System.out.println(event.getName());
    
    }
    

    }
    [/code]
    先生成xml,再解析出来。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码