博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何从Java中打印XML?
阅读量:2292 次
发布时间:2019-05-09

本文共 8773 字,大约阅读时间需要 29 分钟。

本文翻译自:

I have a Java String that contains XML, with no line feeds or indentations. 我有一个包含XML的Java字符串,没有换行符或缩进。 I would like to turn it into a String with nicely formatted XML. 我想把它变成一个格式很好的XML的字符串。 How do I do this? 我该怎么做呢?

String unformattedXml = "
hello
";String formattedXml = new [UnknownClass]().format(unformattedXml);

Note: My input is a String . 注意:我的输入是一个字符串 My output is a String . 我的输出是一个字符串

(Basic) mock result: (基本)模拟结果:

hello

#1楼

参考:


#2楼

I have found that in Java 1.6.0_32 the normal method to pretty print an XML string (using a Transformer with a null or identity xslt) does not behave as I would like if tags are merely separated by whitespace, as opposed to having no separating text. 我发现在Java 1.6.0_32中,相当于打印XML 字符串 (使用带有null或身份xslt的Transformer)的常规方法,如果标签仅由空格分隔,则表现不像我想要的那样,而不是没有分隔文本。 I tried using <xsl:strip-space elements="*"/> in my template to no avail. 我尝试在我的模板中使用<xsl:strip-space elements="*"/>无效。 The simplest solution I found was to strip the space the way I wanted using a SAXSource and XML filter. 我发现最简单的解决方案是使用SAXSource和XML过滤器以我想要的方式剥离空间。 Since my solution was for logging I also extended this to work with incomplete XML fragments. 由于我的解决方案是用于日志记录,我还将其扩展为使用不完整的XML片段。 Note the normal method seems to work fine if you use a DOMSource but I did not want to use this because of the incompleteness and memory overhead. 请注意,如果使用DOMSource,正常方法似乎工作正常,但由于不完整性和内存开销,我不想使用它。

public static class WhitespaceIgnoreFilter extends XMLFilterImpl{    @Override    public void ignorableWhitespace(char[] arg0,                                    int arg1,                                    int arg2) throws SAXException    {        //Ignore it then...    }    @Override    public void characters( char[] ch,                            int start,                            int length) throws SAXException    {        if (!new String(ch, start, length).trim().equals(""))                super.characters(ch, start, length);     }}public static String prettyXML(String logMsg, boolean allowBadlyFormedFragments) throws SAXException, IOException, TransformerException    {        TransformerFactory transFactory = TransformerFactory.newInstance();        transFactory.setAttribute("indent-number", new Integer(2));        Transformer transformer = transFactory.newTransformer();        transformer.setOutputProperty(OutputKeys.INDENT, "yes");        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");        StringWriter out = new StringWriter();        XMLReader masterParser = SAXHelper.getSAXParser(true);        XMLFilter parser = new WhitespaceIgnoreFilter();        parser.setParent(masterParser);        if(allowBadlyFormedFragments)        {            transformer.setErrorListener(new ErrorListener()            {                @Override                public void warning(TransformerException exception) throws TransformerException                {                }                @Override                public void fatalError(TransformerException exception) throws TransformerException                {                }                @Override                public void error(TransformerException exception) throws TransformerException                {                }            });        }        try        {            transformer.transform(new SAXSource(parser, new InputSource(new StringReader(logMsg))), new StreamResult(out));        }        catch (TransformerException e)        {            if(e.getCause() != null && e.getCause() instanceof SAXParseException)            {                if(!allowBadlyFormedFragments || !"XML document structures must start and end within the same entity.".equals(e.getCause().getMessage()))                {                    throw e;                }            }            else            {                throw e;            }        }        out.flush();        return out.toString();    }

#3楼

Now it's 2012 and Java can do more than it used to with XML, I'd like to add an alternative to my accepted answer. 现在是2012年,Java可以比以前用XML更多,我想为我接受的答案添加一个替代方案。 This has no dependencies outside of Java 6. 这与Java 6之外没有依赖关系。

import org.w3c.dom.Node;import org.w3c.dom.bootstrap.DOMImplementationRegistry;import org.w3c.dom.ls.DOMImplementationLS;import org.w3c.dom.ls.LSSerializer;import org.xml.sax.InputSource;import javax.xml.parsers.DocumentBuilderFactory;import java.io.StringReader;/** * Pretty-prints xml, supplied as a string. * 

* eg. * * String formattedXml = new XmlFormatter().format("
hello
"); *
*/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 = Boolean.valueOf(xml.startsWith("
\n" + "
\n" + "
\n" + " \t\t\t\t\t
ECB\n\n\n\n
\n" + "
\n" + "
\n\n\n\n\n" + ""; System.out.println(new XmlFormatter().format(unformattedXml)); }}

#4楼

:

public static String prettyFormat(String input, int indent) {    try {        Source xmlInput = new StreamSource(new StringReader(input));        StringWriter stringWriter = new StringWriter();        StreamResult xmlOutput = new StreamResult(stringWriter);        TransformerFactory transformerFactory = TransformerFactory.newInstance();        transformerFactory.setAttribute("indent-number", indent);        Transformer transformer = transformerFactory.newTransformer();         transformer.setOutputProperty(OutputKeys.INDENT, "yes");        transformer.transform(xmlInput, xmlOutput);        return xmlOutput.getWriter().toString();    } catch (Exception e) {        throw new RuntimeException(e); // simple exception handling, please review it    }}public static String prettyFormat(String input) {    return prettyFormat(input, 2);}

testcase: 测试用例:

prettyFormat("
aaa
");

returns: 收益:

aaa

#5楼

Transformer transformer = TransformerFactory.newInstance().newTransformer();transformer.setOutputProperty(OutputKeys.INDENT, "yes");transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");//initialize StreamResult with File object to save to fileStreamResult result = new StreamResult(new StringWriter());DOMSource source = new DOMSource(doc);transformer.transform(source, result);String xmlString = result.getWriter().toString();System.out.println(xmlString);

Note: Results may vary depending on the Java version. 注意:结果可能因Java版本而异。 Search for workarounds specific to your platform. 搜索特定于您的平台的变通方法。


#6楼

Since you are starting with a String , you need to covert to a DOM object (eg Node ) before you can use the Transformer . 由于您是以String开头的,因此在使用Transformer之前,需要转换为DOM对象(例如Node )。 However, if you know your XML string is valid, and you don't want to incur the memory overhead of parsing a string into a DOM, then running a transform over the DOM to get a string back - you could just do some old fashioned character by character parsing. 但是,如果您知道您的XML字符串是有效的,并且您不希望产生将字符串解析为DOM的内存开销,那么在DOM上运行转换以获取字符串 - 您可以只做一些旧的字符解析。 Insert a newline and spaces after every </...> characters, keep and indent counter (to determine the number of spaces) that you increment for every <...> and decrement for every </...> you see. 在每个</...>字符后面插入换行符和空格,保留和缩进计数器(以确定空格数),为每个<...>递增,并为每个</...>减少。

Disclaimer - I did a cut/paste/text edit of the functions below, so they may not compile as is. 免责声明 - 我对下面的函数进行了剪切/粘贴/文本编辑,因此它们可能无法按原样编译。

public static final Element createDOM(String strXML)     throws ParserConfigurationException, SAXException, IOException {    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();    dbf.setValidating(true);    DocumentBuilder db = dbf.newDocumentBuilder();    InputSource sourceXML = new InputSource(new StringReader(strXML))    Document xmlDoc = db.parse(sourceXML);    Element e = xmlDoc.getDocumentElement();    e.normalize();    return e;}public static final void prettyPrint(Node xml, OutputStream out)    throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException {    Transformer tf = TransformerFactory.newInstance().newTransformer();    tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");    tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");    tf.setOutputProperty(OutputKeys.INDENT, "yes");    tf.transform(new DOMSource(xml), new StreamResult(out));}

转载地址:http://mvcnb.baihongyu.com/

你可能感兴趣的文章
Tomca主配置文件详解
查看>>
Tomcat创建虚拟主机
查看>>
Tomcat集群
查看>>
Tomcat DeltaManager集群共享session
查看>>
Tomcat连接Apache之mod_proxy模块
查看>>
sersync+rsync数据同步
查看>>
使用com.aspose.words将word模板转为PDF文件时乱码解决方法
查看>>
Linux发送邮件
查看>>
YUM安装PHP5.6
查看>>
YUM源安装MySQL5.7
查看>>
Tomcat日志切割cronolog
查看>>
glibc-2.14安装
查看>>
升级openssl zlib版本 安装nginx
查看>>
ab压力测试
查看>>
SVN指定端口启动
查看>>
网站访问速度一般检查参数
查看>>
编译安装过程
查看>>
HTTP常见返回码信息
查看>>
WEB集群session处理方案
查看>>
JDK命令行(jps、jstat、jinfo、jmap、jhat、jstack、jstatd、hprof)与JConsole
查看>>