List of usage examples for org.w3c.dom Document normalizeDocument
public void normalizeDocument();
From source file:Main.java
License:asdf
public static void main(String args[]) throws Exception { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); // Create the parser Document xmlDoc = builder.parse(new InputSource(new StringReader(xmlString))); xmlDoc.normalizeDocument(); }
From source file:DOM3.java
public static void main(String[] argv) { if (argv.length == 0) { printUsage();/*from w w w.j a v a 2 s. c om*/ System.exit(1); } try { // get DOM Implementation using DOM Registry System.setProperty(DOMImplementationRegistry.PROPERTY, "org.apache.xerces.dom.DOMXSImplementationSourceImpl"); DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); // create DOMBuilder builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); DOMConfiguration config = builder.getDomConfig(); // create Error Handler DOMErrorHandler errorHandler = new DOM3(); // create filter LSParserFilter filter = new DOM3(); builder.setFilter(filter); // set error handler config.setParameter("error-handler", errorHandler); // set validation feature // config.setParameter("validate", Boolean.FALSE); config.setParameter("validate", Boolean.TRUE); // set schema language config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema"); // config.setParameter("psvi",Boolean.TRUE); // config.setParameter("schema-type","http://www.w3.org/TR/REC-xml"); // set schema location config.setParameter("schema-location", "personal.xsd"); // parse document System.out.println("Parsing " + argv[0] + "..."); Document doc = builder.parseURI(argv[0]); // set error handler on the Document config = doc.getDomConfig(); config.setParameter("error-handler", errorHandler); // set validation feature config.setParameter("validate", Boolean.TRUE); config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema"); // config.setParameter("schema-type","http://www.w3.org/TR/REC-xml"); config.setParameter("schema-location", "data/personal.xsd"); // remove comments from the document config.setParameter("comments", Boolean.FALSE); System.out.println("Normalizing document... "); doc.normalizeDocument(); // create DOMWriter LSSerializer domWriter = impl.createLSSerializer(); System.out.println("Serializing document... "); config = domWriter.getDomConfig(); config.setParameter("xml-declaration", Boolean.FALSE); // config.setParameter("validate",errorHandler); // serialize document to standard output // domWriter.writeNode(System.out, doc); LSOutput dOut = impl.createLSOutput(); dOut.setByteStream(System.out); domWriter.write(doc, dOut); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:Main.java
/** * Process a w3c XML document into a Java String. * /*from www .ja v a 2 s . c o m*/ * @param outputDoc * @return */ public static String printToString(Document doc) { try { doc.normalizeDocument(); DOMSource source = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(source, result); return writer.toString(); } catch (Exception e) { // e.printStackTrace(); return null; } }
From source file:Main.java
public static String toNormalizedXML(InputStream is) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);/*from w w w . j a v a 2 s . c om*/ dbf.setCoalescing(true); dbf.setIgnoringElementContentWhitespace(true); dbf.setIgnoringComments(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(is); document.normalizeDocument(); document.getDocumentElement().setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", //$NON-NLS-1$ "xsi:schemaLocation", //$NON-NLS-1$ "http://abc4trust.eu/wp2/abcschemav1.0 ../../../../../../../../../abc4trust-xml/src/main/resources/xsd/schema.xsd"); //$NON-NLS-1$ DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation(); LSSerializer serializer = domImplLS.createLSSerializer(); String xml = serializer.writeToString(document); return trim(xml); }
From source file:Main.java
public static boolean compareXmls(InputStream xml1, InputStream xml2) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);// ww w .j a v a 2 s .c o m dbf.setCoalescing(true); dbf.setIgnoringElementContentWhitespace(true); dbf.setIgnoringComments(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc1 = db.parse(xml1); doc1.normalizeDocument(); Document doc2 = db.parse(xml2); doc2.normalizeDocument(); return doc2.isEqualNode(doc1); }
From source file:Main.java
public static void transformDocument(Document document, Writer out, File stylesheet) throws TransformerException { document.normalizeDocument(); Transformer idTransform = null; TransformerFactory transFactory = TransformerFactory.newInstance(); StreamSource stylesource = new StreamSource(stylesheet); idTransform = transFactory.newTransformer(stylesource); Source source = new DOMSource(document); Result result = new StreamResult(out); idTransform.transform(source, result); }
From source file:Main.java
public static void formatDocument(Document document, Writer out, String encoding) throws TransformerException { document.normalizeDocument(); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer idTransform = transFactory.newTransformer(); idTransform.setOutputProperty(OutputKeys.METHOD, "xml"); idTransform.setOutputProperty(OutputKeys.INDENT, "yes"); if (encoding != null) { idTransform.setOutputProperty(OutputKeys.ENCODING, encoding); }//from w ww. j a va2 s. c o m idTransform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source source = new DOMSource(document); Result result = new StreamResult(out); idTransform.transform(source, result); }
From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java
/** * Method used to create enveloped digital signatures for an for a TAXII Inbox_Message (Content_Block and entire Inbox_Message) * * @param doc Document object containing the source XML document * @param keyStorePath Path to KeyStore used for signing document * @param keyStorePW KeyStore password//from w w w .j a v a2 s . co m * @param keyName Alias for private key in KeyStore * @param keyPW Private key password * @return true if successful signing, false otherwise * * Usage Example: * String pks = config.getProperty("pathToPublisherKeyStore"); * String pksPw = FLAREclientUtil.decrypt(config.getProperty("publisherKeyStorePassword")); * String pk = config.getProperty("publisherKeyName"); * String pkPw = FLAREclientUtil.decrypt(config.getProperty("publisherKeyPassword")); * boolean result = Xmldsig.signInboxMessage(taxiiDocument, pks, pksPw, pk, pkPw); */ public static boolean signInboxMessage(Document doc, String keyStorePath, String keyStorePW, String keyName, String keyPW) { doc.normalizeDocument(); PrivateKeyEntry keyEntry = ClientUtil.getKeyEntry(keyStorePath, keyStorePW, keyName, keyPW); if (keyEntry == null) { logger.error( "Error when attempting to digitally sign a document. No key entry found for supplied key-value in config.properties."); return false; } NodeList contentBlockList = doc.getDocumentElement().getElementsByTagNameNS("*", "Content_Block"); if (contentBlockList.getLength() == 0) { logger.error( "Error when attempting to digitally sign a document. No content blocks were present or are not being parsed correctly."); return false; } else { for (int i = 0; i < contentBlockList.getLength(); i++) { Element contentBlock = (Element) contentBlockList.item(i); if (!sign(contentBlock, keyEntry, i + 1)) { return false; } } if (!sign(doc.getDocumentElement(), keyEntry, -1)) { return false; } } return true; }
From source file:Main.java
public static Document createXMLResult(String rootName, Map<String, String> map, Document d) { try {//from ww w . ja va2 s. c o m Element r = d.createElement(rootName); d.appendChild(r); for (String elementName : map.keySet()) { Element eltName = d.createElement(elementName); eltName.appendChild(d.createTextNode(map.get(elementName))); r.appendChild(eltName); } d.normalizeDocument(); return d; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:eu.interedition.collatex.tools.CollationPipe.java
public static void start(CommandLine commandLine) throws Exception { List<SimpleWitness> witnesses = null; Function<String, Stream<String>> tokenizer = SimplePatternTokenizer.BY_WS_OR_PUNCT; Function<String, String> normalizer = SimpleTokenNormalizers.LC_TRIM_WS; Comparator<Token> comparator = new EqualityTokenComparator(); CollationAlgorithm collationAlgorithm = null; boolean joined = true; final String[] witnessSpecs = commandLine.getArgs(); final InputStream[] inputStreams = new InputStream[witnessSpecs.length]; for (int wc = 0, wl = witnessSpecs.length; wc < wl; wc++) { try {//from www . ja v a 2 s . c o m inputStreams[wc] = argumentToInputStream(witnessSpecs[wc]); } catch (MalformedURLException urlEx) { throw new ParseException("Invalid resource: " + witnessSpecs[wc]); } } if (inputStreams.length < 1) { throw new ParseException("No input resource(s) given"); } else if (inputStreams.length < 2) { try (InputStream inputStream = inputStreams[0]) { final SimpleCollation collation = JsonProcessor.read(inputStream); witnesses = collation.getWitnesses(); collationAlgorithm = collation.getAlgorithm(); joined = collation.isJoined(); } } final String script = commandLine.getOptionValue("s"); try { final PluginScript pluginScript = (script == null ? PluginScript.read("<internal>", new StringReader("")) : PluginScript.read(argumentToInput(script))); tokenizer = Optional.ofNullable(pluginScript.tokenizer()).orElse(tokenizer); normalizer = Optional.ofNullable(pluginScript.normalizer()).orElse(normalizer); comparator = Optional.ofNullable(pluginScript.comparator()).orElse(comparator); } catch (IOException e) { throw new ParseException("Failed to read script '" + script + "' - " + e.getMessage()); } switch (commandLine.getOptionValue("a", "").toLowerCase()) { case "needleman-wunsch": collationAlgorithm = CollationAlgorithmFactory.needlemanWunsch(comparator); break; case "medite": collationAlgorithm = CollationAlgorithmFactory.medite(comparator, SimpleToken.TOKEN_MATCH_EVALUATOR); break; case "gst": collationAlgorithm = CollationAlgorithmFactory.greedyStringTiling(comparator, 2); break; default: collationAlgorithm = Optional.ofNullable(collationAlgorithm) .orElse(CollationAlgorithmFactory.dekker(comparator)); break; } if (witnesses == null) { final Charset inputCharset = Charset .forName(commandLine.getOptionValue("ie", StandardCharsets.UTF_8.name())); final boolean xmlMode = commandLine.hasOption("xml"); final XPathExpression tokenXPath = XPathFactory.newInstance().newXPath() .compile(commandLine.getOptionValue("xp", "//text()")); witnesses = new ArrayList<>(inputStreams.length); for (int wc = 0, wl = inputStreams.length; wc < wl; wc++) { try (InputStream stream = inputStreams[wc]) { final String sigil = "w" + (wc + 1); if (!xmlMode) { final BufferedReader reader = new BufferedReader( new InputStreamReader(stream, inputCharset)); final StringWriter writer = new StringWriter(); final char[] buf = new char[1024]; while (reader.read(buf) != -1) { writer.write(buf); } witnesses.add(new SimpleWitness(sigil, writer.toString(), tokenizer, normalizer)); } else { final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); final Document document = documentBuilder.parse(stream); document.normalizeDocument(); final SimpleWitness witness = new SimpleWitness(sigil); final NodeList tokenNodes = (NodeList) tokenXPath.evaluate(document, XPathConstants.NODESET); final List<Token> tokens = new ArrayList<>(tokenNodes.getLength()); for (int nc = 0; nc < tokenNodes.getLength(); nc++) { final String tokenText = tokenNodes.item(nc).getTextContent(); tokens.add(new SimpleToken(witness, tokenText, normalizer.apply(tokenText))); } witness.setTokens(tokens); witnesses.add(witness); } } } } final VariantGraph variantGraph = new VariantGraph(); collationAlgorithm.collate(variantGraph, witnesses); if (joined && !commandLine.hasOption("t")) { VariantGraph.JOIN.apply(variantGraph); } final String output = commandLine.getOptionValue("o", "-"); final Charset outputCharset = Charset .forName(commandLine.getOptionValue("oe", StandardCharsets.UTF_8.name())); final String outputFormat = commandLine.getOptionValue("f", "json").toLowerCase(); try (PrintWriter out = argumentToOutput(output, outputCharset)) { final SimpleVariantGraphSerializer serializer = new SimpleVariantGraphSerializer(variantGraph); if ("csv".equals(outputFormat)) { serializer.toCsv(out); } else if ("dot".equals(outputFormat)) { serializer.toDot(out); } else if ("graphml".equals(outputFormat) || "tei".equals(outputFormat)) { XMLStreamWriter xml = null; try { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(out); xml.writeStartDocument(outputCharset.name(), "1.0"); if ("graphml".equals(outputFormat)) { serializer.toGraphML(xml); } else { serializer.toTEI(xml); } xml.writeEndDocument(); } catch (XMLStreamException e) { throw new IOException(e); } finally { if (xml != null) { try { xml.close(); } catch (XMLStreamException e) { // ignored } } } } else { JsonProcessor.write(variantGraph, out); } } }