JAXB编组器和输出XML的格式

时间:2018-11-08 22:34:04

标签: java jaxb marshalling

我正在关注这篇文章:
JAXB Marshaller indentation

但是我遇到了一个错误:

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

您的评论和意见受到高度赞赏。

干杯,
Artanis Zeratul

1 个答案:

答案 0 :(得分:2)

我通过调整安东尼奥·玛丽亚·桑切斯的答案来解决我的问题。
参考:JAXB Marshaller indentation


所以这是我的答案:

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(instance,stringWriter);
    • 代替使用DOMResult
  • transformer.transform(新的StreamSource(新的StringReader(stringWriter.toString()))  ,new StreamResult(新文件(fullFileNamePath)));
    • 代替使用DOMSource


干杯,
Artanis Zeratul