Java 将字符串转换为 XML 文档以及将 XML 文档转换为字符串
有时在使用 Java 编程时,我们得到的String
实际上是 XML,为了处理它,我们需要将其转换为 XML 文档 ( org.w3c.dom.Document
)。此外,出于调试目的或发送给其他函数,我们可能需要将 Document 对象转换为字符串。这里我提供了两个实用函数。
Document convertStringToDocument(String xmlStr)
:此方法将以字符串形式输入,然后将其转换为 DOM 文档并返回。我们将使用 InputSource 和 StringReader 进行此转换。String convertDocumentToString(Document doc)
:此方法将以 Document 作为输入并将其转换为字符串。我们将为此使用Transformer
和。StringWriter
StreamResult
package com.journaldev.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>Pankaj</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 文档相同的字符串输出。
<?xml version="1.0" encoding="UTF-8"?><Emp id="1"><name>Pankaj</name><age>25</age>
<role>Developer</role><gen>Male</gen></Emp>
您可以使用replaceAll("\n|\r", "")
从字符串中删除换行符并以紧凑格式获取它。