在Java中,可以使用DOM(Document Object Model)或者JAXB(Java Architecture for XML Binding)来生成XML文件。
- 使用DOM:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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;
public class GenerateXML {
public static void main(String[] args) {
try {
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("root");
document.appendChild(rootElement);
Element childElement = document.createElement("child");
childElement.appendChild(document.createTextNode("Hello World"));
rootElement.appendChild(childElement);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File("output.xml"));
transformer.transform(source, result);
System.out.println("XML file generated successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 使用JAXB:
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class GenerateXML {
public static void main(String[] args) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(YourClass.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
YourClass object = new YourClass(); // create an object of your class
marshaller.marshal(object, new File("output.xml"));
System.out.println("XML file generated successfully!");
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
以上代码示例分别使用DOM和JAXB来生成XML文件,你可以根据自己的需求选择其中一种方式实现。