代码之家  ›  专栏  ›  技术社区  ›  Boussadjra Brahim

Java—使用JAXB API从JAXBElement获取XML内容

  •  0
  • Boussadjra Brahim  · 技术社区  · 8 年前

    我有以下代码,它使用JAXB API将医院数据保存到XML文件中,工作正常,但我想将XML内容保存到 String 对象来自 element (the JAXBElement 在保存之前,如果不再次读取该文件,如何在几行代码中完成?

        Wrapper<Hopital> hopitaux = new Wrapper<Hopital>();
                hopitaux.setElements(getListe());
                BufferedWriter writer = new BufferedWriter(new FileWriter(hfile));
    
                JAXBContext context = JAXBContext.newInstance(Wrapper.class, Hopital.class, Service.class, Medecin.class);
                JAXBElement<Wrapper> element = new JAXBElement<Wrapper>(new QName("hopitaux"), Wrapper.class, hopitaux);
                Marshaller m = context.createMarshaller();
                m.setProperty(Marshaller.JAXB_ENCODING, "iso-8859-15");
                m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                m.marshal(element, System.out);
                m.marshal(element, writer);
                writer.close();
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   David Conrad    8 年前

    将其封送至 StringWriter 以字符串形式捕获输出。您必须将编码从 Marshaller 但是,我认为,到了将字符串写入文件的程度。

    StringWriter stringWriter = new StringWriter();
    m.marshal(element, stringWriter);
    String content = stringWriter.toString();
    try (BufferedWriter writer = Files.newBufferedWriter(hfile, 
            Charset.forName("ISO-8859-15"))) {
        writer.write(content);
    }
    

    (假设 hfile 是一个 Path ,否则使用 Paths.get(hfile) hfile.toPath() 视情况而定。)