【问题标题】:Java - Getting XML content from JAXBElement using JAXB APIJava - 使用 JAXB API 从 JAXBElement 获取 XML 内容
【发布时间】:2018-04-19 17:52:18
【问题描述】:

我有以下代码,它使用 JAXB API 将医院数据保存到 XML 文件中,它工作正常,但我想将 XML 内容从 elementJAXBElement 的实例)获取到 String 对象之前保存它而不再次读取文件,我怎样才能在几行代码中做到这一点?

    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();

【问题讨论】:

    标签: java xml jaxb jaxbelement


    【解决方案1】:

    将其编组到 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);
    }
    

    (假设hfilePath,否则酌情使用Paths.get(hfile)hfile.toPath()。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 2012-04-06
      • 2014-10-16
      • 2020-06-22
      • 2011-01-22
      • 1970-01-01
      • 2013-10-30
      相关资源
      最近更新 更多