我正在使用以下代码从String创建com.w3c.dom.Document:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new InputSource(new StringReader("<a><b id="5"/></a>")));
当我System.out.println(xmlToString(文档)),我得到这个:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><a><b id="5"/></a>
一切都还可以,但我不希望XML有<?xml version =“1.0”encoding =“UTF-8”standalone =“no”?>声明,因为我必须用私钥签名并嵌入肥皂信封.
解决方法
@H_404_13@ 您可以使用Transformer
并将
OutputKeys.OMIT_XML_DECLARATION
属性设置为“yes”:
Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); StringWriter sw = new StringWriter(); t.transform(new DOMSource(doc),new StreamResult(sw));
请注意您还可以:
>如果您不需要Document,请使用StreamSource
而不是DOMSource将String直接提供给转换器.
>如果要输出文档,请使用DOMResult
而不是StreamResult.