Java

java怎么根据xml模板生成xml文件

小亿
180
2024-03-07 10:11:58
栏目: 编程语言

在Java中,可以使用DOM(Document Object Model)或者JAXB(Java Architecture for XML Binding)来生成XML文件。

  1. 使用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();
        }
    }
}
  1. 使用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文件,你可以根据自己的需求选择其中一种方式实现。

0
看了该问题的人还看了