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

如何利用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,再解析出来。

    点赞 打赏 评论

相关推荐 更多相似问题