java 有用的Java实用程序类或方法。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 有用的Java实用程序类或方法。相关的知识,希望对你有一定的参考价值。
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Node;
import org.w3c.dom.DOMException;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSException;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Class to format Strings that contain XMLs.
*
* @author Zygimantas
* @see http://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java
*/
public class XmlFormatter {
public String format(String xml) {
try {
final InputSource src = new InputSource(new StringReader(xml));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
final Boolean keepDeclaration = xml.startsWith("<?xml");
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.
return writer.writeToString(document);
} catch (ParserConfigurationException | SAXException | IOException |
ClassNotFoundException | InstantiationException |
IllegalAccessException | ClassCastException | DOMException |
LSException e) {
throw new RuntimeException(e);
}
}
}
以上是关于java 有用的Java实用程序类或方法。的主要内容,如果未能解决你的问题,请参考以下文章