Java Code Examples for org.w3c.dom.Document#getXmlEncoding()

The following examples show how to use org.w3c.dom.Document#getXmlEncoding() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EppMessage.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * A helper method to transform an XML Document to a byte array using the XML Encoding when
 * converting from a String (see xmlDocToString).
 *
 * @param xml the Document to transform
 * @return the resulting byte array.
 * @throws EppClientException if the transform fails
 */
public static byte[] xmlDocToByteArray(Document xml) throws EppClientException {
  try {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(xml);
    transformer.transform(source, result);
    String resultString = result.getWriter().toString();
    if (isNullOrEmpty(resultString)) {
      throw new EppClientException("unknown error converting Document to intermediate string");
    }
    String encoding = xml.getXmlEncoding();
    // this is actually not a problem since we can just use the default
    if (encoding == null) {
      encoding = Charset.defaultCharset().name();
    }
    return resultString.getBytes(encoding);
  } catch (TransformerException | UnsupportedEncodingException e) {
    throw new EppClientException(e);
  }
}
 
Example 2
Source File: DefaultComparisonFormatter.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Appends the XML declaration for {@link #getShortString} or {@link #appendFullDocumentHeader} if it contains
 * non-default values.
 *
 * @param sb the builder to append to
 * @return true if the XML declaration has been appended
 *
 * @since XMLUnit 2.4.0
 */
protected boolean appendDocumentXmlDeclaration(StringBuilder sb, Document doc) {
    if ("1.0".equals(doc.getXmlVersion()) && doc.getXmlEncoding() == null && !doc.getXmlStandalone()) {
        // only default values => ignore
        return false;
    }
    sb.append("<?xml version=\"");
    sb.append(doc.getXmlVersion());
    sb.append("\"");
    if (doc.getXmlEncoding() != null) {
        sb.append(" encoding=\"");
        sb.append(doc.getXmlEncoding());
        sb.append("\"");
    }
    if (doc.getXmlStandalone()) {
        sb.append(" standalone=\"yes\"");
    }
    sb.append("?>");
    return true;
}
 
Example 3
Source File: DOMSerializerImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private String _getXmlEncoding(Node node) {
    Document doc = (node.getNodeType() == Node.DOCUMENT_NODE)
            ? (Document) node : node.getOwnerDocument();
    if (doc != null) {
        try {
            return doc.getXmlEncoding();
        } // The VM ran out of memory or there was some other serious problem. Re-throw.
        catch (VirtualMachineError | ThreadDeath vme) {
            throw vme;
        } // Ignore all other exceptions and errors
        catch (Throwable t) {
        }
    }
    return null;
}
 
Example 4
Source File: DOMSerializerImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private String _getXmlEncoding(Node node) {
    Document doc = (node.getNodeType() == Node.DOCUMENT_NODE)
            ? (Document) node : node.getOwnerDocument();
    if (doc != null) {
        try {
            return doc.getXmlEncoding();
        } // The VM ran out of memory or there was some other serious problem. Re-throw.
        catch (VirtualMachineError | ThreadDeath vme) {
            throw vme;
        } // Ignore all other exceptions and errors
        catch (Throwable t) {
        }
    }
    return null;
}
 
Example 5
Source File: XMLIndentUtil.java    From rest-client with Apache License 2.0 5 votes vote down vote up
public static String getIndented(String inXml) throws IOException {
    try {
        final InputSource src = new InputSource(new StringReader(inXml));
        final Document domDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src);
        String encoding = domDoc.getXmlEncoding();
        if (encoding == null) {
            // defaults to UTF-8
            encoding = "UTF-8";
        }
        final Node document = domDoc.getDocumentElement();
        final boolean keepDeclaration = inXml.startsWith("<?xml");
        final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        final LSSerializer writer = impl.createLSSerializer();
        writer.setNewLine("\n");
        writer.getDomConfig().setParameter("format-pretty-print", true); // Set this to true if the output needs to be beautified.
        writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.
        LSOutput lsOutput = impl.createLSOutput();
        lsOutput.setEncoding(encoding);
        Writer stringWriter = new StringWriter();
        lsOutput.setCharacterStream(stringWriter);
        writer.write(document, lsOutput);
        return stringWriter.toString();
    }
    catch (ParserConfigurationException | SAXException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
        throw new XMLException(null, ex);
    }
}
 
Example 6
Source File: DocumentUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a String representation for the XML Document.
 *
 * @param xmlDocument the XML Document
 * @return String representation for the XML Document
 * @throws IOException
 */
public static String documentToString(Document xmlDocument) throws IOException {
    String encoding = (xmlDocument.getXmlEncoding() == null) ? "UTF-8" : xmlDocument.getXmlEncoding();
    OutputFormat format = new OutputFormat(xmlDocument);
    format.setLineWidth(65);
    format.setIndenting(true);
    format.setIndent(2);
    format.setEncoding(encoding);
    try (Writer out = new StringWriter()) {
        XMLSerializer serializer = new XMLSerializer(out, format);
        serializer.serialize(xmlDocument);
        return out.toString();
    }
}
 
Example 7
Source File: SVGDocument.java    From latexdraw with GNU General Public License v3.0 5 votes vote down vote up
/**
 * The constructor. An URI defines the location of the SVG document to parse. If the document is valid,
 * the document is read an place in the <code>root</code> attribute.
 * @param uri The file to parse.
 * @throws IOException If the document cannot be opened.
 * @throws IllegalArgumentException If an argument is not valid.
 */
public SVGDocument(final URI uri) throws IOException {
	super();
	if(uri == null) {
		throw new IllegalArgumentException();
	}

	final DocumentBuilder builder = SystemUtils.getInstance().createXMLDocumentBuilder()
		.orElseThrow(() -> new IllegalArgumentException());

	builder.setEntityResolver(new SVGEntityResolver());
	final Document doc = readXMLDocument(builder, uri.getPath())
		.orElseGet(() -> readXMLDocument(builder, "file:" + uri.getPath()).orElse(null));

	if(doc == null) {
		throw new IOException("Cannot open the XML document " + uri);
	}

	final NodeList nl;

	setXmlStandalone(doc.getXmlStandalone());
	setXmlVersion(doc.getXmlVersion());
	xmlEncoding = doc.getXmlEncoding();
	root = null;
	nl = doc.getChildNodes();
	Node n;

	for(int i = 0, size = nl.getLength(); i < size && root == null; i++) {
		n = nl.item(i);

		if(n instanceof Element && n.getNodeName().endsWith(SVGElements.SVG_SVG)) {
			root = new SVGSVGElement(this, nl.item(i));
		}
	}
}
 
Example 8
Source File: XmlPayloadIO.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * @see io.apiman.gateway.engine.io.IPayloadIO#marshall(java.lang.Object)
 */
@Override
public byte[] marshall(Document data) throws Exception {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(data);
    transformer.transform(source, result);
    String xml = result.getWriter().toString();
    String enc = data.getXmlEncoding();
    if (enc == null) {
        enc = "UTF8"; //$NON-NLS-1$
    }
    return xml.getBytes(enc);
}