java xml文件输出
时间: 2023-07-11 20:09:33 浏览: 93
java读取跟输出xml文件
您可以使用Java中的DOM或SAX库来输出XML文件。以下是使用DOM库的示例代码:
```java
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XMLWriter {
public static void main(String[] args) {
try {
// 创建DocumentBuilderFactory和DocumentBuilder对象
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// 创建一个新的XML文档
Document doc = docBuilder.newDocument();
// 创建根节点
Element rootElement = doc.createElement("employees");
doc.appendChild(rootElement);
// 创建子节点
Element employee = doc.createElement("employee");
rootElement.appendChild(employee);
// 添加属性
employee.setAttribute("id", "1");
// 添加子节点
Element firstName = doc.createElement("firstName");
firstName.appendChild(doc.createTextNode("John"));
employee.appendChild(firstName);
Element lastName = doc.createElement("lastName");
lastName.appendChild(doc.createTextNode("Doe"));
employee.appendChild(lastName);
Element age = doc.createElement("age");
age.appendChild(doc.createTextNode("28"));
employee.appendChild(age);
// 将文档写入XML文件
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("employees.xml"));
transformer.transform(source, result);
System.out.println("XML文件已创建");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们创建了一个名为“employees.xml”的新XML文件,并将其写入“employees”根元素及其子元素和属性。
阅读全文