gpt4 book ai didi

java - JAXB 编码器和输出 XML 格式

转载 作者:行者123 更新时间:2023-11-30 01:59:59 24 4
gpt4 key购买 nike

我正在关注这篇文章:
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);

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

干杯,
阿塔尼斯·泽拉图

最佳答案

我通过稍微调整安东尼奥·玛丽亚·桑切斯的答案解决了我的问题。
引用: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(实例, stringWriter);
    • 而不是使用 DOMResult
  • transformer.transform(new StreamSource(new StringReader(stringWriter.toString())) ,new StreamResult(new File(fullFileNamePath)));
    • 而不是使用 DOMSource


干杯,
阿塔尼斯·泽拉图

关于java - JAXB 编码器和输出 XML 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53217170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com