Java读取 XML 文件并将 XML 字符串打印到控制台或者将 XML 写入文件 示例
www. On IT Road .com
Java从文件中读取 XML
将 XML 从 .xml文件读取到 Document对象的示例。
private static Document convertXMLFileToXMLDocument(String filePath)
{
//Parser that produces DOM object trees from XML content
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//API to obtain DOM Document instance
DocumentBuilder builder = null;
try
{
//Create DocumentBuilder with default configuration
builder = factory.newDocumentBuilder();
//Parse the content to Document object
Document xmlDocument = builder.parse(new File(filePath));
return xmlDocument;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
将 XML 转换为字符串
要将 XML 对象例如:org.w3c.dom.Document转换为字符串,我们需要以下类:
javax.xml.transform.Transformer:这个类的一个实例可以使用它的transform()方法将源树转换为结果树。javax.xml.transform.TransformerFactory:创建Transformer实例的工厂。javax.xml.transform.dom.DOMSource:文档对象模型(DOM)树形式的源树。javax.xml.transform.stream.StreamResult:转换结果树的持有者,可以是 XML、纯文本、HTML 或者某种其他形式的标记。
将 XML 打印到控制台或者日志文件
private static void writeXmlDocumentToXmlFile(Document xmlDocument)
{
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = tf.newTransformer();
// Uncomment if you do not require XML declaration
// transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
//A character stream that collects its output in a string buffer,
//which can then be used to construct a string.
StringWriter writer = new StringWriter();
//transform document to string
transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer));
String xmlString = writer.getBuffer().toString();
System.out.println(xmlString); //Print to console or logs
}
catch (TransformerException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
将 XML 写入文件
private static void writeXmlDocumentToXmlFile(Document xmlDocument, String fileName)
{
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = tf.newTransformer();
//Uncomment if you do not require XML declaration
//transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
//Write XML to file
FileOutputStream outStream = new FileOutputStream(new File(fileName));
transformer.transform(new DOMSource(xmlDocument), new StreamResult(outStream));
}
catch (TransformerException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
日期:2020-09-17 00:10:13 来源:oir作者:oir
