当前位置:  开发笔记 > 编程语言 > 正文

如何从Java中打印XML?

如何解决《如何从Java中打印XML?》经验,为你挑选了18个好方法。

我有一个包含XML的Java字符串,没有换行符或缩进.我想把它变成一个格式很好的XML的字符串.我该怎么做呢?

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

注意:我的输入是一个字符串.我的输出是一个字符串.

(基本)模拟结果:



  
    hello
  

Lorenzo Bocc.. 257

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 file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);

注意:结果可能因Java版本而异.搜索特定于您的平台的变通方法.



1> Lorenzo Bocc..:
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 file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);

注意:结果可能因Java版本而异.搜索特定于您的平台的变通方法.


要省略`<?xml ...>`声明,添加`​​transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes")`
休闲读者可能会发现这里描述的解决方案的改进版本(http://stackoverflow.com/a/33541820/363573).
这不回答我的问题:如何格式化包含XML的String?这个答案已经假定您已经以某种方式将String对象转换为另一个对象.

2> Steve McLeod..:

这是我自己的问题的答案.我将各种结果的答案结合起来,编写了一个非常适合打印XML的类.

无法保证它如何响应无效的XML或大型文档.

package ecb.sdw.pretty;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

/**
 * Pretty-prints xml, supplied as a string.
 * 

* eg. * * String formattedXml = new XmlFormatter().format("hello"); * */ public class XmlFormatter { public XmlFormatter() { } public String format(String unformattedXml) { try { final Document document = parseXmlFile(unformattedXml); OutputFormat format = new OutputFormat(document); format.setLineWidth(65); format.setIndenting(true); format.setIndent(2); Writer out = new StringWriter(); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(document); return out.toString(); } catch (IOException e) { throw new RuntimeException(e); } } private Document parseXmlFile(String in) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(in)); return db.parse(is); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } public static void main(String[] args) { String unformattedXml = "\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)); } }


早在2008年,这是一个很好的答案,但现在这一切都可以用标准的JDK类而不是Apache类来完成.请参见http://xerces.apache.org/xerces2-j/faq-general.html#faq-6.是的,这是一个Xerces FAQ,但答案涵盖了标准的JDK类.这些类的最初1.5实现有很多问题,但从1.6开始一切正常.复制常见问题解答中的LSSerializer示例,切断"..."位并添加`writer.getDomConfig().setParameter("format-pretty-print",Boolean.TRUE);```LSSerializer writer = ... `线.
请注意,这个答案需要使用Xerces.如果您不想添加此依赖项,那么您只需使用标准的jdk库和javax.xml.transform.Transformer(请参阅下面的答案)
我使用Apache给出的示例创建了一个小类,@ GeorgeHawkins给出了一个链接.它错过了变量`document`的初始化方式,所以我想我可以加减速并做一个快速的例子.让我知道我是否应该改变一些东西,http://pastebin.com/XL7932aC

3> dfa..:

基于这个答案的更简单的解决方案:

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);
}

测试用例:

prettyFormat("aaa");

收益:



  aaa
  


@Harry:`transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");`
嗨我正在使用这个确切的代码,我的格式正确,除了第一个元素所以,这个:`<?xml version ="1.0"encoding ="UTF-8"?> `全部在一行.有什么想法吗?
@Codemiester:似乎是一个bug(见http://stackoverflow.com/a/18251901/3375325).添加`transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"yes");`为我工作.

4> Steve McLeod..:

现在是2012年,Java可以比以前用XML更多,我想为我接受的答案添加一个替代方案.这与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)); } }


@DanTemple看起来您需要使用LSOutput来控制编码.见http://www.chipkillmar.net/2009/03/25/pretty-print-xml-from-a-dom/

5> khylo..:

请注意,评分最高的答案需要使用xerces.

如果您不想添加此外部依赖项,那么您可以简单地使用标准的jdk库(实际上是使用内部的xerces构建的).

NB有一个jdk版本1.5的错误请参见http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446但现在已经解决.

(注意如果发生错误,这将返回原始文本)

package com.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

public class XmlTest {
    public static void main(String[] args) {
        XmlTest t = new XmlTest();
        System.out.println(t.formatXml("text D"));
    }

    public String formatXml(String xml){
        try{
            Transformer serializer= SAXTransformerFactory.newInstance().newTransformer();
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            //serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            //serializer.setOutputProperty("{http://xml.customer.org/xslt}indent-amount", "2");
            Source xmlSource=new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
            StreamResult res =  new StreamResult(new ByteArrayOutputStream());            
            serializer.transform(xmlSource, res);
            return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
        }catch(Exception e){
            //TODO log error
            return xml;
        }
    }

}


应该不需要转换为字节数组/字符串.至少在这样做时你必须指定charset.更好的选择是使用包含在InputSource和StreamResult中的StringReader和StringWriter类.

6> mlo55..:

我以前使用org.dom4j.io.OutputFormat.createPrettyPrint()方法打印了

public String prettyPrint(final String xml){  

    if (StringUtils.isBlank(xml)) {
        throw new RuntimeException("xml was null or blank in prettyPrint()");
    }

    final StringWriter sw;

    try {
        final OutputFormat format = OutputFormat.createPrettyPrint();
        final org.dom4j.Document document = DocumentHelper.parseText(xml);
        sw = new StringWriter();
        final XMLWriter writer = new XMLWriter(sw, format);
        writer.write(document);
    }
    catch (Exception e) {
        throw new RuntimeException("Error pretty printing xml:\n" + xml, e);
    }
    return sw.toString();
}


在我的情况下,接受的解决方案没有正确地缩进嵌套标签,这个.
我结合使用它来删除行尾的所有尾随空格:`prettyPrintedString.replaceAll("\\ s + \n","\n")`

7> Mark Pope..:

这是使用dom4j执行此操作的一种方法:

进口:

import org.dom4j.Document;  
import org.dom4j.DocumentHelper;  
import org.dom4j.io.OutputFormat;  
import org.dom4j.io.XMLWriter;

码:

String xml = "";  
Document doc = DocumentHelper.parseText(xml);  
StringWriter sw = new StringWriter();  
OutputFormat format = OutputFormat.createPrettyPrint();  
XMLWriter xw = new XMLWriter(sw, format);  
xw.write(doc);  
String result = sw.toString();



8> Kevin Hakans..:

由于您是以a开头的String,因此在使用之前需要转换为DOM对象(例如Node)Transformer.但是,如果您知道您的XML字符串是有效的,并且您不希望产生将字符串解析为DOM的内存开销,那么在DOM上运行转换以获取字符串 - 您可以只做一些旧的字符解析.在每个字符后插入换行符和空格,保留和缩进计数器(以确定空格数),每增加一个,<...>并为每个看到的减量递减.

免责声明 - 我对下面的函数进行了剪切/粘贴/文本编辑,因此它们可能无法按原样编译.

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));
}



9> Jonik..:

如果使用第三方XML库是可以的,那么您可以使用比当前最高投票 答案所暗示的更简单的东西.

有人说输入和输出都应该是字符串,所以这里有一个实用方法就是这样,用XOM库实现:

import nu.xom.*;
import java.io.*;

[...]

public static String format(String xml) throws ParsingException, IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Serializer serializer = new Serializer(out);
    serializer.setIndent(4);  // or whatever you like
    serializer.write(new Builder().build(xml, ""));
    return out.toString("UTF-8");
}

我测试它是否有效,结果依赖于您的JRE版本或类似的东西.要了解如何根据自己的喜好自定义输出格式,请查看SerializerAPI.

这实际上出来的时间比我想-是需要一些额外的线路,因为Serializer希望有一个OutputStream写.但请注意,这里实际的XML错误代码非常少.

(这个答案是我XOM的评价,这是部分建议,如我一个选项对最好的Java XML库问题更换dom4j中为了记录在案,与dom4j中你可以使用同样轻松地实现这一目标.XMLWriterOutputFormat.编辑:.. .在mlo55的答案中证明了.)


谢谢,这就是我在寻找的东西.如果在"Document"对象中已经使用XOM解析了XML,则可以将其直接传递给serializer.write(document);

10> 小智..:

嗯...面对这样的事情,这是一个已知的bug ...只需添加此OutputProperty ..

transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "8");

希望这可以帮助 ...



11> David Easley..:

Kevin Hakanson说:"但是,如果您知道您的XML字符串是有效的,并且您不希望产生将字符串解析为DOM的内存开销,那么在DOM上运行转换以获取字符串 - 您可以通过字符解析来做一些老式的字符.在每个字符后插入换行符和空格,保留和缩进计数器(以确定空格的数量),每增加一个<...>,然后递减每个字符."

同意.这种方法更快,并且依赖性更低.

示例解决方案

/**
 * XML utils, including formatting.
 */
public class XmlUtils
{
  private static XmlFormatter formatter = new XmlFormatter(2, 80);

  public static String formatXml(String s)
  {
    return formatter.format(s, 0);
  }

  public static String formatXml(String s, int initialIndent)
  {
    return formatter.format(s, initialIndent);
  }

  private static class XmlFormatter
  {
    private int indentNumChars;
    private int lineLength;
    private boolean singleLine;

    public XmlFormatter(int indentNumChars, int lineLength)
    {
      this.indentNumChars = indentNumChars;
      this.lineLength = lineLength;
    }

    public synchronized String format(String s, int initialIndent)
    {
      int indent = initialIndent;
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < s.length(); i++)
      {
        char currentChar = s.charAt(i);
        if (currentChar == '<')
        {
          char nextChar = s.charAt(i + 1);
          if (nextChar == '/')
            indent -= indentNumChars;
          if (!singleLine)   // Don't indent before closing element if we're creating opening and closing elements on a single line.
            sb.append(buildWhitespace(indent));
          if (nextChar != '?' && nextChar != '!' && nextChar != '/')
            indent += indentNumChars;
          singleLine = false;  // Reset flag.
        }
        sb.append(currentChar);
        if (currentChar == '>')
        {
          if (s.charAt(i - 1) == '/')
          {
            indent -= indentNumChars;
            sb.append("\n");
          }
          else
          {
            int nextStartElementPos = s.indexOf('<', i);
            if (nextStartElementPos > i + 1)
            {
              String textBetweenElements = s.substring(i + 1, nextStartElementPos);

              // If the space between elements is solely newlines, let them through to preserve additional newlines in source document.
              if (textBetweenElements.replaceAll("\n", "").length() == 0)
              {
                sb.append(textBetweenElements + "\n");
              }
              // Put tags and text on a single line if the text is short.
              else if (textBetweenElements.length() <= lineLength * 0.5)
              {
                sb.append(textBetweenElements);
                singleLine = true;
              }
              // For larger amounts of text, wrap lines to a maximum line length.
              else
              {
                sb.append("\n" + lineWrap(textBetweenElements, lineLength, indent, null) + "\n");
              }
              i = nextStartElementPos - 1;
            }
            else
            {
              sb.append("\n");
            }
          }
        }
      }
      return sb.toString();
    }
  }

  private static String buildWhitespace(int numChars)
  {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < numChars; i++)
      sb.append(" ");
    return sb.toString();
  }

  /**
   * Wraps the supplied text to the specified line length.
   * @lineLength the maximum length of each line in the returned string (not including indent if specified).
   * @indent optional number of whitespace characters to prepend to each line before the text.
   * @linePrefix optional string to append to the indent (before the text).
   * @returns the supplied text wrapped so that no line exceeds the specified line length + indent, optionally with
   * indent and prefix applied to each line.
   */
  private static String lineWrap(String s, int lineLength, Integer indent, String linePrefix)
  {
    if (s == null)
      return null;

    StringBuilder sb = new StringBuilder();
    int lineStartPos = 0;
    int lineEndPos;
    boolean firstLine = true;
    while(lineStartPos < s.length())
    {
      if (!firstLine)
        sb.append("\n");
      else
        firstLine = false;

      if (lineStartPos + lineLength > s.length())
        lineEndPos = s.length() - 1;
      else
      {
        lineEndPos = lineStartPos + lineLength - 1;
        while (lineEndPos > lineStartPos && (s.charAt(lineEndPos) != ' ' && s.charAt(lineEndPos) != '\t'))
          lineEndPos--;
      }
      sb.append(buildWhitespace(indent));
      if (linePrefix != null)
        sb.append(linePrefix);

      sb.append(s.substring(lineStartPos, lineEndPos + 1));
      lineStartPos = lineEndPos + 1;
    }
    return sb.toString();
  }

  // other utils removed for brevity
}


这是应该完成的方式。在字符串级别即时格式化。这是唯一格式化无效或不完整XML的解决方案。

12> StaxMan..:

关于"你必须首先构建一个DOM树"的评论:不,你不需要也不应该这样做.

相反,创建一个StreamSource(新的StreamSource(新的StringReader(str)),并将其提供给所提到的身份变换器.这将使用SAX解析器,结果将更快.在这种情况下构建中间树是纯粹的开销.否则排名靠前的答案是好的.



13> Synesso..:

使用scala:

import xml._
val xml = XML.loadString("hello")
val formatted = new PrettyPrinter(150, 2).format(xml)
println(formatted)

如果依赖于scala-library.jar,也可以在Java中执行此操作.它看起来像这样:

import scala.xml.*;

public class FormatXML {
    public static void main(String[] args) {
        String unformattedXml = "hello";
        PrettyPrinter pp = new PrettyPrinter(150, 3);
        String formatted = pp.format(XML.loadString(unformattedXml), TopScope$.MODULE$);
        System.out.println(formatted);
    }
}

PrettyPrinter对象由两个整数构成,第一个是最大行长度,第二个是缩进步骤.



14> codeskraps..:

来自milosmns的略有改进的版本......

public static String getPrettyXml(String xml) {
    if (xml == null || xml.trim().length() == 0) return "";

    int stack = 0;
    StringBuilder pretty = new StringBuilder();
    String[] rows = xml.trim().replaceAll(">", ">\n").replaceAll("<", "\n<").split("\n");

    for (int i = 0; i < rows.length; i++) {
        if (rows[i] == null || rows[i].trim().length() == 0) continue;

        String row = rows[i].trim();
        if (row.startsWith("") == false) {
            String indent = repeatString(stack++);
            pretty.append(indent + row + "\n");
            if (row.endsWith("]]>")) stack--;
        } else {
            String indent = repeatString(stack);
            pretty.append(indent + row + "\n");
        }
    }

    return pretty.toString().trim();
}

private static String repeatString(int stack) {
     StringBuilder indent = new StringBuilder();
     for (int i = 0; i < stack; i++) {
        indent.append(" ");
     }
     return indent.toString();
} 


private static String repeatString(int stack){StringBuilder indent = new StringBuilder(); for(int i = 0; i
15> Michael..:

仅供将来参考,这是一个适合我的解决方案(感谢@George Hawkins在其中一个答案中发表的评论):

DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
LSOutput output = impl.createLSOutput();
ByteArrayOutputStream out = new ByteArrayOutputStream();
output.setByteStream(out);
writer.write(document, output);
String xmlStr = new String(out.toByteArray());



16> milosmns..:

如果您确定自己拥有有效的XML,那么这个XML很简单,并且避免使用XML DOM树.也许有一些错误,如果你看到任何东西就做评论

public String prettyPrint(String xml) {
            if (xml == null || xml.trim().length() == 0) return "";

            int stack = 0;
            StringBuilder pretty = new StringBuilder();
            String[] rows = xml.trim().replaceAll(">", ">\n").replaceAll("<", "\n<").split("\n");

            for (int i = 0; i < rows.length; i++) {
                    if (rows[i] == null || rows[i].trim().length() == 0) continue;

                    String row = rows[i].trim();
                    if (row.startsWith("


private static String repeatString(int stack){StringBuilder indent = new StringBuilder(); for(int i = 0; i 哪里是repeatString方法..?

17> Georgy Goboz..:

以上所有解决方案都不适合我,然后我发现这个http://myshittycode.com/2014/02/10/java-properly-indenting-xml-string/

线索是用XPath删除空格

    String xml = "" +
             "\n   " +
             "\nCoco Puff" +
             "\n        10    ";

try {
    Document document = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder()
            .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']",
                                                  document,
                                                  XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node node = nodeList.item(i);
        node.getParentNode().removeChild(node);
    }

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);

    transformer.transform(new DOMSource(document), streamResult);

    System.out.println(stringWriter.toString());
}
catch (Exception e) {
    e.printStackTrace();
}



18> 小智..:

我将所有这些混合在一起并编写一个小程序。它正在从xml文件读取并打印出来。只是xzy而不是提供您的文件路径。

    public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new FileInputStream(new File("C:/Users/xyz.xml")));
    prettyPrint(doc);

}

private static String prettyPrint(Document document)
        throws TransformerException {
    TransformerFactory transformerFactory = TransformerFactory
            .newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    DOMSource source = new DOMSource(document);
    StringWriter strWriter = new StringWriter();
    StreamResult result = new StreamResult(strWriter);transformer.transform(source, result);
    System.out.println(strWriter.getBuffer().toString());

    return strWriter.getBuffer().toString();

}

推荐阅读
手机用户2402851335
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有