java生成xml文件
时间: 2023-10-10 07:14:16 浏览: 92
在Java中可以使用DOM或者SAX来生成XML文件,下面分别介绍使用这两种方式生成XML文件的方法。
1. 使用DOM生成XML文件
DOM方式是将整个XML文件读入内存中,然后以树形结构进行操作。下面是使用DOM方式生成XML文件的示例代码:
```java
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.w3c.dom.Element;
public class GenerateXML {
public static void main(String[] args) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// 创建根节点
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("30"));
employee.appendChild(age);
// 创建子节点
Element gender = doc.createElement("gender");
gender.appendChild(doc.createTextNode("Male"));
employee.appendChild(gender);
// 创建TransformerFactory对象
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
// 将XML文件写入磁盘
StreamResult result = new StreamResult(new File("employees.xml"));
transformer.transform(source, result);
System.out.println("XML文件生成成功!");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
}
```
运行该程序后,会在当前目录下生成一个名为employees.xml的XML文件,内容如下:
```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<employees>
<employee id="1">
<firstName>John</firstName>
<lastName>Doe</lastName>
<age>30</age>
<gender>Male</gender>
</employee>
</employees>
```
2. 使用SAX生成XML文件
SAX方式是一种基于事件驱动的XML解析方式,它不需要将整个XML文件读入内存中,而是在解析XML文件时逐个读取XML元素,以达到节省内存的目的。下面是使用SAX方式生成XML文件的示例代码:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class GenerateXML {
public static void main(String[] args) {
try {
// 创建一个SAXParserFactory实例
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
// 创建一个DefaultHandler实例
DefaultHandler handler = new DefaultHandler() {
boolean bFirstName = false;
boolean bLastName = false;
boolean bAge = false;
boolean bGender = false;
// 开始解析XML元素时调用该方法
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("employee")) {
System.out.println("开始解析员工信息");
} else if (qName.equalsIgnoreCase("firstName")) {
bFirstName = true;
} else if (qName.equalsIgnoreCase("lastName")) {
bLastName = true;
} else if (qName.equalsIgnoreCase("age")) {
bAge = true;
} else if (qName.equalsIgnoreCase("gender")) {
bGender = true;
}
}
// 解析XML元素时获取元素内容时调用该方法
public void characters(char ch[], int start, int length) throws SAXException {
if (bFirstName) {
System.out.println("员工名:" + new String(ch, start, length));
bFirstName = false;
} else if (bLastName) {
System.out.println("员工姓:" + new String(ch, start, length));
bLastName = false;
} else if (bAge) {
System.out.println("员工年龄:" + new String(ch, start, length));
bAge = false;
} else if (bGender) {
System.out.println("员工性别:" + new String(ch, start, length));
bGender = false;
}
}
// 结束解析XML元素时调用该方法
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("employee")) {
System.out.println("结束解析员工信息");
}
}
};
// 开始解析XML文件
saxParser.parse(new File("employees.xml"), handler);
// 将XML文件写入磁盘
FileWriter writer = new FileWriter("employees2.xml");
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
writer.write("<employees>\n");
writer.write("<employee>\n");
writer.write("<firstName>John</firstName>\n");
writer.write("<lastName>Doe</lastName>\n");
writer.write("<age>30</age>\n");
writer.write("<gender>Male</gender>\n");
writer.write("</employee>\n");
writer.write("</employees>\n");
writer.close();
System.out.println("XML文件生成成功!");
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
运行该程序后,会在当前目录下生成一个名为employees2.xml的XML文件,内容如下:
```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<employees>
<employee>
<firstName>John</firstName>
<lastName>Doe</lastName>
<age>30</age>
<gender>Male</gender>
</employee>
</employees>
```
阅读全文