Last active
September 2, 2015 18:59
-
-
Save leogaldioli/198855901c1b2824448a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static byte[] canonicalizeXml(final String aXML) { | |
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); | |
DocumentBuilder builder = null; | |
try { | |
InputSource is = new InputSource(); | |
is.setCharacterStream(new StringReader(aXML)); | |
builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false); | |
builder = builderFactory.newDocumentBuilder(); | |
Document xmlDocument = builder.parse(is); | |
Node infNFe = xmlDocument.getElementsByTagName("infNFe").item(0); | |
NamedNodeMap infNFeattributes = infNFe.getAttributes(); | |
String versao = infNFeattributes.getNamedItem("versao").getTextContent(); | |
infNFeattributes.removeNamedItem("versao"); | |
Attr attrVersao = xmlDocument.createAttribute("versao"); | |
attrVersao.setValue(versao); | |
infNFeattributes.setNamedItem(attrVersao); | |
xmlDocument.getDomConfig().setParameter("canonical-form",true); // EXCEPTION org.w3c.dom.DOMException: FEATURE_NOT_SUPPORTED: O parâmetro canonical-form é reconhecido, mas o valor solicitado não pode ser definido. | |
return getXmlString(xmlDocument).getBytes(StandardCharsets.UTF_8); | |
} catch (Exception e) { | |
throw new EspdNeverStopUtilsException(TspdConstMessages.UTILS_ERRO_TAG, className, e.getMessage()); | |
} | |
} | |
private static String getXmlString(Document xmlDocument) | |
throws TransformerConfigurationException, | |
TransformerFactoryConfigurationError, TransformerException { | |
Transformer transformer = TransformerFactory.newInstance().newTransformer(); | |
transformer.setOutputProperty(OutputKeys.INDENT, "no"); | |
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); | |
//initialize StreamResult with File object to save to file | |
StreamResult result = new StreamResult(new StringWriter()); | |
DOMSource source = new DOMSource(xmlDocument); | |
transformer.transform(source, result); | |
return result.getWriter().toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment