在Java中,可以使用DOM(Document Object Model)或者JAXB(Java Architecture for XML Binding)來生成XML文件。
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();
}
}
}
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文件,你可以根據自己的需求選擇其中一種方式實現。