如何删除xml文档中的独立属性声明?

2022-09-01 01:35:28

我目前正在使用Java创建一个xml,然后我将其转换为字符串。xml 声明如下所示:

DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
doc.setXmlVersion("1.0");

为了将文档转换为 String,我包括以下声明:

TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
trans.setOutputProperty(OutputKeys.VERSION, "1.0");
trans.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
trans.setOutputProperty(OutputKeys.INDENT, "yes");

然后我做转换:

StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();

问题是,在 XML 声明属性中,包含独立属性,我不希望这样,但我希望显示版本和编码属性:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

是否有任何可以指定的属性?


答案 1

根据我所读到的内容,您可以在创建之前调用以下方法来执行此操作:DocumentDOMSource

doc.setXmlStandalone(true); //before creating the DOMSource

如果设置了它,则无法控制它是否显示。等等。在变压器中,如果你想要一个输出使用任何“是”或“否”你需要。如果在 中设置了什么(如果设置),输出将始终保持为falsesetXmlStandalone(true)DocumentOutputKeyssetXmlStandalone(false)Documentstandalone="no"Transformer

阅读此论坛中的帖子


答案 2