2013-02-07 18 views
5

sto creando un com.w3c.dom.Document da un String utilizzando questo codice:com.w3c.dom.Document senza <? Xml version = "1.0" encoding = "UTF-8" standalone = "no"?>

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); 
Document doc = docBuilder.parse(new InputSource(new StringReader("<a><b id="5"/></a>"))); 

Quando ho System.out.println(xmlToString(document)), ottengo questo:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><a><b id="5"/></a> 

Tutto è ok, ma io non voglio che il XML avere la dichiarazione <?xml version="1.0" encoding="UTF-8" standalone="no"?>, perché devo firmare la con la chiave privata e incorporare a busta sapone.

risposta

11

si potrebbe usare un Transformer e impostare la OutputKeys.OMIT_XML_DECLARATION proprietà "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)); 

Si prega di notare che si poteva anche:

  • Utilizzare un StreamSource invece di un DOMSource per alimentare la String direttamente al trasformatore, se non hai davvero bisogno del Document.
  • Utilizzare un DOMResult invece di un StreamResult se si desidera produrre un Document.
+0

Grazie! Ora ho altri problemi, cercando di risolverli da solo! :) –

Problemi correlati