Im am currently creating an xml using Java and then I transform it into a String. The xml declaration is as follows:
Im目前正在使用Java创建xml,然后我将它转换为字符串。xml声明如下:
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
doc.setXmlVersion("1.0");
For transforming the document into String, I include the following declaration:
为了将文件转换为字符串,我包括以下声明:
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");
And then I do the transformation:
然后进行变换
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
The problem is that in the XML Declaration attributes, the standalone attribute is included and I don't want that, but I want the version and encoding attributes to appear:
问题在于,在XML声明属性中,包含了独立属性,我不想要它,但是我想要显示的版本和编码属性:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
Is there any property where that could be specified?
是否有可以指定的属性?
1 个解决方案
#1
34
From what I've read you can do this by calling the below method on Document
before creating the DOMSource
在创建DOMSource之前,可以通过调用Document上的下面的方法来实现这一点
doc .setXmlStandalone(true); //before creating the DOMSource
Other comments
其他评论
If you set it "false" you cannot control it to appear or not. So setXmlStandalone(true) on Document. In transformer if you want an output use OutputKeys with whatever "yes" or "no" you need. If you setXmlStandalone(false) on Document your output will be always standalone="no" no matter what you set (if you set) in Transformer.
如果设置为“false”,则无法控制它是否出现。所以setXmlStandalone(真正的)文档。在transformer中,如果你想要一个输出,可以使用OutputKeys来表示你需要的“是”或“不是”。如果您在文档上设置了xmlindependence (false),那么无论您在Transformer中设置了什么(如果设置了),输出始终是独立的=“no”。
Read the thread in this forum
请阅读本论坛的相关文章
#1
34
From what I've read you can do this by calling the below method on Document
before creating the DOMSource
在创建DOMSource之前,可以通过调用Document上的下面的方法来实现这一点
doc .setXmlStandalone(true); //before creating the DOMSource
Other comments
其他评论
If you set it "false" you cannot control it to appear or not. So setXmlStandalone(true) on Document. In transformer if you want an output use OutputKeys with whatever "yes" or "no" you need. If you setXmlStandalone(false) on Document your output will be always standalone="no" no matter what you set (if you set) in Transformer.
如果设置为“false”,则无法控制它是否出现。所以setXmlStandalone(真正的)文档。在transformer中,如果你想要一个输出,可以使用OutputKeys来表示你需要的“是”或“不是”。如果您在文档上设置了xmlindependence (false),那么无论您在Transformer中设置了什么(如果设置了),输出始终是独立的=“no”。
Read the thread in this forum
请阅读本论坛的相关文章