Java 写入 XML
Sheeraz Gul
2023年10月12日
Java 内置的文档对象模型 API 用于在 Java 中创建和写入 XML 文件。本教程演示如何将 XML 写入 Java 中的控制台和文件。
Java 写入 XML
如上所述,DOM API 用于将 XML 写入 Java 中的文件。这是一个用 Java 将 XML 写入文件的简单示例。
package Delfstack;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Write_XML {
public static void main(String[] args) throws ParserConfigurationException, TransformerException {
DocumentBuilderFactory Doc_Build_Factory = DocumentBuilderFactory.newInstance();
DocumentBuilder Document_Builder = Doc_Build_Factory.newDocumentBuilder();
// the root elements for DOM Document
// create XML fields, elements, etc.
Document document = Document_Builder.newDocument();
Element Root_Element = document.createElement("School");
document.appendChild(Root_Element);
document.createElement("Teacher");
Root_Element.appendChild(document.createElement("Teacher"));
document.createElement("Student");
Root_Element.appendChild(document.createElement("Student"));
// write DOM document in a file
try (FileOutputStream output_file = new FileOutputStream("school.xml")) {
Write_Xml(document, output_file);
System.out.println("The XML has been successfully written to school.xml");
} catch (IOException e) {
e.printStackTrace();
}
}
// Method to generate XML. Writing output stream
private static void Write_Xml(Document document, OutputStream output_file)
throws TransformerException {
TransformerFactory Transformer_Factory = TransformerFactory.newInstance();
Transformer New_Transformer = Transformer_Factory.newTransformer();
DOMSource Source_XML = new DOMSource(document);
StreamResult Result_XML = new StreamResult(output_file);
New_Transformer.transform(Source_XML, Result_XML);
}
}
上面的代码将创建一个文件并向其写入 XML 语法。见输出:
The XML has been successfully written to school.xml
让我们尝试另一个包含更多字段的示例,该示例将 XML 写入文件和控制台。参见示例:
package Delfstack;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Write_XML {
public static void main(String[] args) {
DocumentBuilderFactory Doc_Builder_Factory = DocumentBuilderFactory.newInstance();
DocumentBuilder Document_Builder;
try {
Document_Builder = Doc_Builder_Factory.newDocumentBuilder();
Document document = Document_Builder.newDocument();
// adding elements to Document
Element Root_Element = document.createElementNS("https://www.delftstack.com/", "Tutorials");
document.appendChild(Root_Element);
// add a first child element to the root element
Root_Element.appendChild(Get_Tutorial(document, "1",
"Perform String to String Array Conversion in Java",
"https://www.delftstack.com/howto/java/how-to-perform-string-to-string-array-conversion-in-java/",
"Java", "May-21, 2020"));
// add a second child
Root_Element.appendChild(Get_Tutorial(document, "2", "Compile a C++ Program Using GCC",
"https://www.delftstack.com/howto/cpp/gcc-compile-cpp/", "C++", "March-25, 2022"));
// add third child
Root_Element.appendChild(Get_Tutorial(document, "3", "Python Tutorial - Introduction",
"https://www.delftstack.com/tutorial/python-3-basic-tutorial/python-introduction/",
"Python", "January-29, 2018"));
// create output
TransformerFactory Transformer_Factory = TransformerFactory.newInstance();
Transformer transformer = Transformer_Factory.newTransformer();
// open indent for the xml code
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource Dom_Source = new DOMSource(document);
// write to file and console both
StreamResult XML_file = new StreamResult(new File("delftstack.xml"));
StreamResult XML_console = new StreamResult(System.out);
// write data
transformer.transform(Dom_Source, XML_file);
transformer.transform(Dom_Source, XML_console);
System.out.println("The XML Has been written to the file and console");
} catch (Exception e) {
e.printStackTrace();
}
}
private static Node Get_Tutorial(Document document, String id, String article_name, String link,
String programming_language, String date_created) {
Element tutorial = document.createElement("Tutorial");
// set the tutorial id attribute
tutorial.setAttribute("Id", id);
// create article name element
tutorial.appendChild(Get_Tutorial_Elements(document, tutorial, "ArticleName", article_name));
// create the Link element
tutorial.appendChild(Get_Tutorial_Elements(document, tutorial, "Link", link));
// create the Programming Language element
tutorial.appendChild(
Get_Tutorial_Elements(document, tutorial, "ProgrammingLanguage", programming_language));
// create Date Created element
tutorial.appendChild(Get_Tutorial_Elements(document, tutorial, "DateCreated", date_created));
return tutorial;
}
// method to create text node
private static Node Get_Tutorial_Elements(
Document document, Element element, String element_name, String element_value) {
Element element_node = document.createElement(element_name);
element_node.appendChild(document.createTextNode(element_value));
return element_node;
}
}
上面的代码将为 delftstack.com
的教程创建一个 XML 文件。每个教程包含四个字段,ArticleName
、Link
、ProgrammingLanguage
和 DateCreated
。
该代码将创建 XML 文件并将 XML 写入控制台。查看输出:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Tutorials xmlns="https://www.delftstack.com/">
<Tutorial Id="1">
<ArticleName>Perform String to String Array Conversion in Java</ArticleName>
<Link>https://www.delftstack.com/howto/java/how-to-perform-string-to-string-array-conversion-in-java/</Link>
<ProgrammingLanguage>Java</ProgrammingLanguage>
<DateCreated>May-21, 2020</DateCreated>
</Tutorial>
<Tutorial Id="2">
<ArticleName>Compile a C++ Program Using GCC</ArticleName>
<Link>https://www.delftstack.com/howto/cpp/gcc-compile-cpp/</Link>
<ProgrammingLanguage>C++</ProgrammingLanguage>
<DateCreated>March-25, 2022</DateCreated>
</Tutorial>
<Tutorial Id="3">
<ArticleName>Python Tutorial - Introduction</ArticleName>
<Link>https://www.delftstack.com/tutorial/python-3-basic-tutorial/python-introduction/</Link>
<ProgrammingLanguage>Python</ProgrammingLanguage>
<DateCreated>January-29, 2018</DateCreated>
</Tutorial>
</Tutorials>
The XML Has been written to the file and console
作者: Sheeraz Gul
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook