org.w3c.dom.ls.LSOutput#setEncoding ( )源码实例Demo

下面列出了org.w3c.dom.ls.LSOutput#setEncoding ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: latexdraw   文件: SVGDocument.java
/**
 * Serialise the given SVG document.
 * @param path The file of the future serialised document.
 * @return True: the document has been successfully saved.
 */
public boolean saveSVGDocument(final String path) {
	if(path == null) {
		return false;
	}

	boolean ok = true;
	try {
		final DOMImplementationLS impl = (DOMImplementationLS) DOMImplementationRegistry.newInstance().getDOMImplementation("XML 3.0 LS 3.0"); //NON-NLS
		final LSSerializer serializer = impl.createLSSerializer();
		serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); //NON-NLS
		serializer.getDomConfig().setParameter("namespaces", Boolean.FALSE); //NON-NLS
		final LSOutput output = impl.createLSOutput();
		final Charset charset = Charset.defaultCharset();
		try(final OutputStreamWriter fw = new OutputStreamWriter(Files.newOutputStream(Path.of(path)), charset.newEncoder())) {
			output.setEncoding(charset.name());
			output.setCharacterStream(fw);
			serializer.write(getDocumentElement(), output);
		}
	}catch(final ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException | IOException ex) {
		BadaboomCollector.INSTANCE.add(ex);
		ok = false;
	}
	return ok;
}
 
源代码2 项目: simplexml   文件: Formatter.java
private void format(Document document, Writer writer) {
   DOMImplementation implementation = document.getImplementation();

   if(implementation.hasFeature(LS_FEATURE_KEY, LS_FEATURE_VERSION) && implementation.hasFeature(CORE_FEATURE_KEY, CORE_FEATURE_VERSION)) {
      DOMImplementationLS implementationLS = (DOMImplementationLS) implementation.getFeature(LS_FEATURE_KEY, LS_FEATURE_VERSION);
      LSSerializer serializer = implementationLS.createLSSerializer();
      DOMConfiguration configuration = serializer.getDomConfig();
      
      configuration.setParameter("format-pretty-print", Boolean.TRUE);
      configuration.setParameter("comments", preserveComments);
      
      LSOutput output = implementationLS.createLSOutput();
      output.setEncoding("UTF-8");
      output.setCharacterStream(writer);
      serializer.write(document, output);
   }
}
 
源代码3 项目: openhab1-addons   文件: Helper.java
/***
 * Helper method which converts XML Document into pretty formatted string
 *
 * @param doc to convert
 * @return converted XML as String
 */
public static String documentToString(Document doc) {

    String strMsg = "";
    try {
        DOMImplementation domImpl = doc.getImplementation();
        DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
        LSSerializer lsSerializer = domImplLS.createLSSerializer();
        lsSerializer.getDomConfig().setParameter("format-pretty-print", true);

        Writer stringWriter = new StringWriter();
        LSOutput lsOutput = domImplLS.createLSOutput();
        lsOutput.setEncoding("UTF-8");
        lsOutput.setCharacterStream(stringWriter);
        lsSerializer.write(doc, lsOutput);
        strMsg = stringWriter.toString();
    } catch (Exception e) {
        logger.warn("Error occurred when converting document to string", e);
    }
    return strMsg;
}
 
源代码4 项目: teamengine   文件: CoverageMonitor.java
/**
 * Writes a DOM Document to the given OutputStream using the "UTF-8"
 * encoding. The XML declaration is omitted.
 * 
 * @param outStream
 *            The destination OutputStream object.
 * @param doc
 *            A Document node.
 */
void writeDocument(OutputStream outStream, Document doc) {
    DOMImplementationRegistry domRegistry = null;
    try {
        domRegistry = DOMImplementationRegistry.newInstance();
    // Fortify Mod: Broaden try block to capture all potential exceptions
    // } catch (Exception e) {
    //    LOGR.warning(e.getMessage());
    // }
    DOMImplementationLS impl = (DOMImplementationLS) domRegistry
            .getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();
    writer.getDomConfig().setParameter("xml-declaration", false);
    writer.getDomConfig().setParameter("format-pretty-print", true);
    LSOutput output = impl.createLSOutput();
    output.setEncoding("UTF-8");
    output.setByteStream(outStream);
    writer.write(doc, output);
    } catch (Exception e) {
        LOGR.warning(e.getMessage());
    }
}
 
源代码5 项目: netbeans   文件: WebBrowserImpl.java
private void _dumpDocument( Document doc, String title ) {
    if( null == title || title.isEmpty() ) {
        title = NbBundle.getMessage(WebBrowserImpl.class, "Lbl_GenericDomDumpTitle");
    }
    InputOutput io = IOProvider.getDefault().getIO( title, true );
    io.select();
    try {
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation( "XML 3.0 LS 3.0" ); //NOI18N
        if( null == impl ) {
            io.getErr().println( NbBundle.getMessage(WebBrowserImpl.class, "Err_DOMImplNotFound") );
            return;
        }


        LSSerializer serializer = impl.createLSSerializer();
        if( serializer.getDomConfig().canSetParameter( "format-pretty-print", Boolean.TRUE ) ) { //NOI18N
            serializer.getDomConfig().setParameter( "format-pretty-print", Boolean.TRUE ); //NOI18N
        }
        LSOutput output = impl.createLSOutput();
        output.setEncoding("UTF-8"); //NOI18N
        output.setCharacterStream( io.getOut() );
        serializer.write(doc, output);
        io.getOut().println();

    } catch( Exception ex ) {
        ex.printStackTrace( io.getErr() );
    } finally {
        if( null != io ) {
            io.getOut().close();
            io.getErr().close();
        }
    }
}
 
源代码6 项目: lams   文件: OrganisationGroupServlet.java
@SuppressWarnings("unchecked")
   private void getGroupings(Integer organisationId, HttpServletResponse response) throws IOException {
Document doc = OrganisationGroupServlet.docBuilder.newDocument();
Element groupsElement = doc.createElement("groups");
doc.appendChild(groupsElement);

List<OrganisationGrouping> groupings = userManagementService.findByProperty(OrganisationGrouping.class,
	"organisationId", organisationId);
for (OrganisationGrouping grouping : groupings) {
    Element groupingElement = doc.createElement("grouping");
    groupingElement.setAttribute("id", grouping.getGroupingId().toString());
    groupingElement.setAttribute("name", StringEscapeUtils.escapeXml(grouping.getName()));
    groupsElement.appendChild(groupingElement);
    for (OrganisationGroup group : grouping.getGroups()) {
	Element groupElement = doc.createElement("group");
	groupElement.setAttribute("id", group.getGroupId().toString());
	groupElement.setAttribute("name", StringEscapeUtils.escapeXml(group.getName()));
	groupingElement.appendChild(groupElement);
	for (User user : group.getUsers()) {
	    Element userElement = doc.createElement("user");
	    userElement.setAttribute("id", user.getUserId().toString());
	    userElement.setAttribute("firstname", StringEscapeUtils.escapeXml(user.getFirstName()));
	    userElement.setAttribute("lastname", StringEscapeUtils.escapeXml(user.getLastName()));
	    groupElement.appendChild(userElement);
	}
    }
}

response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");

DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
LSOutput lsOutput = domImplementation.createLSOutput();
lsOutput.setEncoding("UTF-8");
lsOutput.setByteStream(response.getOutputStream());
lsSerializer.write(doc, lsOutput);
   }
 
源代码7 项目: scipio-erp   文件: UtilXml.java
/** Returns a <code>LSOutput</code> instance.
 * @param impl A <code>DOMImplementationLS</code> instance
 * @param os Optional <code>OutputStream</code> instance
 * @param encoding Optional character encoding, default is UTF-8
 * @return A <code>LSOutput</code> instance
 * @see <a href="http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407/">DOM Level 3 Load and Save Specification</a>
 */
public static LSOutput createLSOutput(DOMImplementationLS impl, OutputStream os, String encoding) {
    LSOutput out = impl.createLSOutput();
    if (os != null) {
        out.setByteStream(os);
    }
    if (encoding != null) {
        out.setEncoding(encoding);
    }
    return out;
}
 
源代码8 项目: TranskribusCore   文件: CoreUtils.java
/**
	 * from: https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java
	 * @param xml The string representation of the unformatted XML
	 * @return The string representation of the formatted XML
	 * @throws ClassCastException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws ClassNotFoundException 
	 * @throws ParserConfigurationException 
	 * @throws IOException 
	 * @throws SAXException 
	 * @deprecated does it work with correct encoding?
	 */
	public static String formatXml(String xml) throws ClassNotFoundException, InstantiationException, IllegalAccessException, ClassCastException, SAXException, IOException, ParserConfigurationException {
//		try {
			final InputSource src = new InputSource(new StringReader(xml));
			final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src)
					.getDocumentElement();
			final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));

			// May need this:
			// System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");

			final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
			final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
			final LSSerializer writer = impl.createLSSerializer();

			writer.getDomConfig().setParameter("format-pretty-print", Boolean.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("UTF-8");
			             StringWriter stringWriter = new StringWriter();
			             lsOutput.setCharacterStream(stringWriter);
			             writer.write(document, lsOutput);
			             return stringWriter.toString();

//			return writer.writeToString(document);
//		} catch (Exception e) {
//			throw new RuntimeException(e);
//		}
	}
 
源代码9 项目: dsl-json   文件: XmlConverter.java
public static void serialize(final Element value, final JsonWriter sw) {
	Document document = value.getOwnerDocument();
	DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
	LSSerializer serializer = domImplLS.createLSSerializer();
	LSOutput lsOutput = domImplLS.createLSOutput();
	lsOutput.setEncoding("UTF-8");
	StringWriter writer = new StringWriter();
	lsOutput.setCharacterStream(writer);
	serializer.write(document, lsOutput);
	StringConverter.serialize(writer.toString(), sw);
}
 
源代码10 项目: pixymeta-android   文件: XMLUtils.java
/**
 * Serialize XML Node to string
 * <p>
 * Note: this method is supposed to be faster than the Transform version but the output control
 * is limited. If node is Document node, it will output XML PI which sometimes we want to avoid.
 * 
 * @param doc XML document
 * @param node Node to be serialized
 * @param encoding encoding for the output
 * @return String representation of the Document
 * @throws IOException
 */
public static String serializeToStringLS(Document doc, Node node, String encoding) throws IOException {
	DOMImplementationLS domImpl = (DOMImplementationLS) doc.getImplementation();
       LSSerializer lsSerializer = domImpl.createLSSerializer();
       LSOutput output = domImpl.createLSOutput();
       output.setEncoding(encoding);
       StringWriter writer = new StringWriter();
       output.setCharacterStream(writer);
       lsSerializer.write(node, output);
       writer.flush();
       
       return writer.toString();
}
 
源代码11 项目: sakai   文件: ConvertUserFavoriteSitesSakai11.java
private String toXML(Document doc) {
    StringWriter result = new StringWriter();

    DOMImplementation impl = documentBuilder.getDOMImplementation();
    DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = feature.createLSSerializer();
    LSOutput lsoutput = feature.createLSOutput();
    lsoutput.setCharacterStream(result);
    lsoutput.setEncoding("UTF-8");
    serializer.write(doc, lsoutput);

    result.flush();

    return result.toString();
}
 
源代码12 项目: sakai   文件: StorageUtils.java
/**
 * Write a DOM Document to an output stream.
 * 
 * @param doc
 *        The DOM Document to write.
 * @param out
 *        The output stream.
 */
public static String writeDocumentToString(Document doc)
{
	try
	{
		
		StringWriter sw = new StringWriter();
		
		  DocumentBuilder builder = dbFactory.newDocumentBuilder();
		  DOMImplementation impl = builder.getDOMImplementation();
		  
		
		DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS",
		"3.0");
		LSSerializer serializer = feature.createLSSerializer();
		LSOutput output = feature.createLSOutput();
		output.setCharacterStream(sw);
		output.setEncoding("UTF-8");
		serializer.write(doc, output);
		
		sw.flush();
		return sw.toString();
	}
	catch (Exception any)
	{
		log.warn("writeDocumentToString: " + any.toString());
		return null;
	}
}
 
源代码13 项目: sakai   文件: Xml.java
/**
 * Write a DOM Document to an output stream.
 * 
 * @param doc
 *        The DOM Document to write.
 * @param out
 *        The output stream.
 */
public static String writeDocumentToString(Document doc)
{
	try
	{
		
		StringWriter sw = new StringWriter();
		
		 DocumentBuilderFactory factory 
		   = DocumentBuilderFactory.newInstance();
		  DocumentBuilder builder = factory.newDocumentBuilder();
		  DOMImplementation impl = builder.getDOMImplementation();
		  
		
		DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS",
		"3.0");
		LSSerializer serializer = feature.createLSSerializer();
		LSOutput output = feature.createLSOutput();
		output.setCharacterStream(sw);
		output.setEncoding("UTF-8");
		serializer.write(doc, output);
		
		sw.flush();
		return sw.toString();
	}
	catch (Exception any)
	{
		log.warn("writeDocumentToString: " + any.toString());
		return null;
	}
}
 
源代码14 项目: icafe   文件: XMLUtils.java
/**
 * Serialize XML Node to string
 * <p>
 * Note: this method is supposed to be faster than the Transform version but the output control
 * is limited. If node is Document node, it will output XML PI which sometimes we want to avoid.
 * 
 * @param doc XML document
 * @param node Node to be serialized
 * @param encoding encoding for the output
 * @return String representation of the Document
 * @throws IOException
 */
public static String serializeToStringLS(Document doc, Node node, String encoding) throws IOException {
	DOMImplementationLS domImpl = (DOMImplementationLS) doc.getImplementation();
       LSSerializer lsSerializer = domImpl.createLSSerializer();
       LSOutput output = domImpl.createLSOutput();
       output.setEncoding(encoding);
       StringWriter writer = new StringWriter();
       output.setCharacterStream(writer);
       lsSerializer.write(node, output);
       writer.flush();
       
       return writer.toString();
}
 
源代码15 项目: rest-client   文件: XMLIndentUtil.java
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);
    }
}
 
源代码16 项目: sakai   文件: ConvertUserFavoriteSitesSakai11.java
private String toXML(Document doc) {
    StringWriter result = new StringWriter();

    DOMImplementation impl = documentBuilder.getDOMImplementation();
    DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = feature.createLSSerializer();
    LSOutput lsoutput = feature.createLSOutput();
    lsoutput.setCharacterStream(result);
    lsoutput.setEncoding("UTF-8");
    serializer.write(doc, lsoutput);

    result.flush();

    return result.toString();
}
 
源代码17 项目: archistar-core   文件: XmlDocumentBuilder.java
public String stringFromDoc(Document doc) {
    DOMImplementation impl = doc.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer lsSerializer = implLS.createLSSerializer();
    lsSerializer.getDomConfig().setParameter("format-pretty-print", true);

    LSOutput lsOutput = implLS.createLSOutput();
    lsOutput.setEncoding("UTF-8");
    Writer stringWriter = new StringWriter();
    lsOutput.setCharacterStream(stringWriter);
    lsSerializer.write(doc, lsOutput);

    return stringWriter.toString();
}
 
源代码18 项目: intellij-xquery   文件: ExistRunnerApp.java
private String prettyPrint(Element node) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    DOMImplementationRegistry domImplementationRegistry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementationRegistry.getDOMImplementation("LS");
    LSOutput lsOutput = domImplementationLS.createLSOutput();
    LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
    lsOutput.setEncoding("UTF-8");
    Writer stringWriter = new StringWriter();
    lsOutput.setCharacterStream(stringWriter);
    lsSerializer.write(node, lsOutput);
    String result = stringWriter.toString();
    return result;
}
 
源代码19 项目: aion-germany   文件: CompoundXmlRequest.java
public String toXml()
{
    Document document;
    DocumentBuilder docBuilder;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try
    {
        docBuilder = factory.newDocumentBuilder();
        document = docBuilder.newDocument();
    }
    catch (ParserConfigurationException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
    DOMImplementationLS implLS = (DOMImplementationLS) docBuilder.getDOMImplementation();
    LSSerializer domWriter = implLS.createLSSerializer();
    LSOutput output = implLS.createLSOutput();
    
    //DOMException: FEATURE_NOT_SUPPORTED: The parameter format-pretty-print is recognized but the requested value cannot be set.
    //domWriter.getDomConfig().setParameter(Constants.DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);
    
    output.setEncoding("UTF-8");
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    output.setByteStream(outStream);
    
    
    Element root = document.createElement("requests");
    for(Request req : _requests)
    {
        Element reqNode = document.createElement("request");
        reqNode.setAttribute("id", Integer.toString(req.getId()));
        reqNode.setAttribute("type", req.getType());
        for(RequestPart part : req.getParts())
        {
            Element partNode = null;
            if(part instanceof RequestForPart)
            {
                partNode = document.createElement("for");
                writeForPart(partNode, (RequestForPart) part, document);
            }
            else
            {
                partNode = document.createElement("part");
                partNode.setAttribute("name", part.getName());
                partNode.setAttribute("value", part.getValue());
            }
            reqNode.appendChild(partNode);
        }
        root.appendChild(reqNode);
    }
    
    document.appendChild(root);
    domWriter.write(document, output);
    
    return outStream.toString();
}
 
源代码20 项目: lams   文件: NotificationServlet.java
private void getNotifications(Integer userId, HttpServletRequest request, HttpServletResponse response)
    throws IOException {
Document doc = NotificationServlet.docBuilder.newDocument();
Element notificationsElement = doc.createElement("Notifications");
doc.appendChild(notificationsElement);

Long lessonId = WebUtil.readLongParam(request, CentralConstants.PARAM_LESSON_ID, true);
Integer limit = WebUtil.readIntParam(request, "limit", true);
Integer offset = WebUtil.readIntParam(request, "offset", true);
Boolean pendingOnly = WebUtil.readBooleanParam(request, "pendingOnly", true);

List<Subscription> subscriptions = eventNotificationService
	.getNotificationSubscriptions(lessonId, userId, pendingOnly, limit, offset);
for (Subscription subscription : subscriptions) {
    Element notificationElement = doc.createElement("Notification");

    notificationElement.setAttribute("id", subscription.getUid().toString());

    Boolean pending = !DeliveryMethodNotification.LAST_OPERATION_SEEN
	    .equals(subscription.getLastOperationMessage());
    notificationElement.setAttribute("pending", pending.toString());

    Long notificationLessonId = subscription.getEvent().getEventSessionId();
    if (notificationLessonId != null) {
	notificationElement.setAttribute("lessonId", notificationLessonId.toString());
    }

    String message = subscription.getEvent().getMessage();
    Matcher matcher = NotificationServlet.anchorPattern.matcher(message);
    if (matcher.find()) {
	String href = StringEscapeUtils.escapeXml(matcher.group(2));
	notificationElement.setAttribute("href", href);
	message = matcher.group(3);
    }
    notificationElement.appendChild(doc.createCDATASection(message));

    notificationsElement.appendChild(notificationElement);
}

response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");

DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
LSOutput lsOutput = domImplementation.createLSOutput();
lsOutput.setEncoding("UTF-8");
lsOutput.setByteStream(response.getOutputStream());
lsSerializer.write(doc, lsOutput);
   }