Java将字符串转换为XML文档,并将XML文档转换为String

时间:2020-02-23 14:36:28  来源:igfitidea点击:

有时在用Java编程时,我们会得到实际上是XML的String,并且要对其进行处理,我们需要将其转换为XML Document(org.w3c.dom.Document)。
同样出于调试目的或者发送给其他功能,我们可能需要将Document对象转换为String。

其中我提供了两个实用程序功能。

  • Document convertStringToDocument(String xmlStr):此方法将输入作为String,然后将其转换为DOM Document并返回。
    我们将使用InputSource和StringReader进行此转换。

  • String convertDocumentToString(Document doc):该方法将输入作为Document并将其转换为String。
    为此,我们将使用Transformer,StringWriter和StreamResult。

package com.theitroad.xml;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class StringToDocumentToString {

  public static void main(String[] args) {
      final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
                              "<Emp id=\"1\"><name>hyman</name><age>25</age>\n"+
                              "<role>Developer</role><gen>Male</gen></Emp>";
      Document doc = convertStringToDocument(xmlStr);
      
      String str = convertDocumentToString(doc);
      System.out.println(str);
  }

  private static String convertDocumentToString(Document doc) {
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer;
      try {
          transformer = tf.newTransformer();
          //below code to remove XML declaration
          //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
          StringWriter writer = new StringWriter();
          transformer.transform(new DOMSource(doc), new StreamResult(writer));
          String output = writer.getBuffer().toString();
          return output;
      } catch (TransformerException e) {
          e.printStackTrace();
      }
      
      return null;
  }

  private static Document convertStringToDocument(String xmlStr) {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
      DocumentBuilder builder;  
      try  
      {  
          builder = factory.newDocumentBuilder();  
          Document doc = builder.parse( new InputSource( new StringReader( xmlStr ) ) ); 
          return doc;
      } catch (Exception e) {  
          e.printStackTrace();  
      } 
      return null;
  }

}

当我们在上面的程序中运行时,我们将获得与用于创建DOM Document相同的String输出。

<?xml version="1.0" encoding="UTF-8"?><Emp id="1"><name>hyman</name><age>25</age>
<role>Developer</role><gen>Male</gen></Emp>

您可以使用replaceAll(" \ n | \ r","")从String中删除新行字符,并以紧凑格式获取它。