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

Java 如何删除xml文档中的独立属性声明?,java,xml,dom,Java,Xml,Dom,我目前正在使用Java创建一个xml,然后将其转换为字符串。xml声明如下所示: DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); doc.setXmlVersion("1.0"); 为了将文档转换为字符串,我包含

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

DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
doc.setXmlVersion("1.0");
为了将文档转换为字符串,我包含以下声明:

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"?>


是否有可以指定的属性?

根据我所读的内容,在创建
DOMSource
之前,您可以通过调用
文档中的以下方法来执行此操作:

doc.setXmlStandalone(true); //before creating the DOMSource
如果将其设置为
false
,则无法控制其是否显示。所以
setXmlStandalone(true)
on
Document
。在transformer中,如果您想要输出,请使用
OutputKeys
和您需要的任何“是”或“否”。如果在
Document
setXmlStandalone(false)
,无论在
Transformer
中设置了什么(如果设置),您的输出将始终是
standalone=“no”


出于好奇阅读

,你为什么要摆脱
standalone=“no”
?毕竟,缺少
standalone
属性相当于
standalone=“no”
:“如果没有外部标记声明,则独立文档声明没有意义。如果有外部标记声明,但没有独立文档声明,则假定值为“no”因为我目前正在开发一个电子发票生成系统。为了生成发票,我需要创建一个xml,它应该遵循SAT(在墨西哥)所做的规范。如果不遵循规范,发票将无效。说明XML文档必须符合某种格式约定的规范,即XML信息模型内容之外的规范,需要进行后处理。XML序列化程序通常无法满足有关序列化的任意规范。(我指的是信息科学意义上的“任意性”,而不是“随机性”)在Windows 7上的Sun Java 1.6.035的输出中,我仍然得到standalone=“no”。您还可以将transformer-OutputKeys.standalone的属性设置为true@JanHruby它应该被设置为“是”@Pangea它可以工作,但当我这样做时,它不再在序言后打印换行符了!setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,“”);导致在prolog之后添加新行