使用Java创建XML文件可以通过使用Java的DOM(Document Object Model)或者JAXB(Java Architecture for XML Binding)来实现。
示例代码:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class CreateXML {
public static void main(String[] args) {
try {
// 创建DocumentBuilderFactory实例
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
// 创建根元素
Element rootElement = doc.createElement("root");
doc.appendChild(rootElement);
// 创建子元素
Element childElement = doc.createElement("child");
rootElement.appendChild(childElement);
// 设置子元素的属性和值
childElement.setAttribute("attribute", "value");
childElement.setTextContent("Hello World!");
// 将DOM树写入XML文件
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("output.xml"));
transformer.transform(source, result);
System.out.println("XML文件创建成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
示例代码:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.File;
public class CreateXML {
public static void main(String[] args) {
try {
// 创建JAXBContext实例
JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
Marshaller marshaller = jaxbContext.createMarshaller();
// 设置Marshaller的属性
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// 创建根元素对象
Root root = new Root();
root.setChild(new Child("value", "Hello World!"));
// 将根元素对象写入XML文件
marshaller.marshal(root, new File("output.xml"));
System.out.println("XML文件创建成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
class Root {
private Child child;
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
}
class Child {
private String attribute;
private String value;
public Child() {}
public Child(String attribute, String value) {
this.attribute = attribute;
this.value = value;
}
@XmlAttribute
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
@XmlElement
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
以上是使用Java创建XML文件的两种常用方式。在实际应用中,可以根据具体需求选择适合的方式来创建XML文件。
领取专属 10元无门槛券
手把手带您无忧上云