JAXB 编组器和输出格式 XML

JAXB Marshaller and Formatting of output XML

我在关注这个 post:

但是我运行一个错误:

org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.

这实际上与我使用过的 Marshaller 有关:

marshaller.marshal(instance, domResult);

非常感谢您的评论和意见。

干杯,
阿塔尼斯泽拉图

我通过稍微调整 Antonio Maria Sanchez 的回答解决了我的问题。
参考:


所以这是我的答案:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class ObjectToXMLWriter {
    public static <Type> boolean writeToFileWithXmlTransformer(Type instance
            ,String fullFileNamePath) throws FileNotFoundException {
        boolean isSaved = false;
        JAXBContext jaxBContent = null;
        Marshaller marshaller = null;
        StringWriter stringWriter = new StringWriter();

        try {
            jaxBContent = JAXBContext.newInstance(instance.getClass());
            marshaller = jaxBContent.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(instance, stringWriter);

            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            transformer.transform(new StreamSource(new StringReader(stringWriter.toString()))
                    ,new StreamResult(new File(fullFileNamePath)));

           isSaved = true; 
        } catch(JAXBException jaxBException) {
            System.out.println("JAXBException happened!");
            jaxBException.printStackTrace();
        } catch(Exception exception) {
            System.out.println("Exception happened!");
            exception.printStackTrace();
        }

        return isSaved;
    }
}


该答案的关键点如下:

  • marshaller.marshal(实例, stringWriter);
    • 而不是使用 DOMResult
  • transformer.transform(新 StreamSource(新 StringReader(stringWriter.toString())) ,new StreamResult(new File(fullFileNamePath)));
    • 而不是使用 DOMSource


干杯,
阿塔尼斯泽拉图