話不多說,代碼如下:
public class BuildXmlUtil {
public static void main(String[] args) throws Exception {
buildxml();
}
public static void buildxml() throws ParserConfigurationException, TransformerException{
//step1:獲得一個DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//step2:獲得一個DocumentBuilder
DocumentBuilder db = factory.newDocumentBuilder();
//step3:新建一個Document對象
Document document = db.newDocument();
//step4:創建一個根節點
Element rootElement = document.createElement("engineering");
for (int i=0;i<3;i++){
//step5:創建一個節點
Element person = document.createElement("engineering");
//step6:為該節點設定屬性
person.setAttribute("id", "id_");
Element name = document.createElement("name");
//為節點設定文本內容
name.setTextContent("name_");
Element author = document.createElement("author");
author.setTextContent("author_");
Element addressUrl = document.createElement("addressUrl");
addressUrl.setTextContent("addressUrl_");
person.appendChild(name);
person.appendChild(author);
person.appendChild(addressUrl);
//step7:為某一元素節點設立子節點
rootElement.appendChild(person);
}
//step8:把剛剛建立的根節點添加到document對象中
document.appendChild(rootElement);
//step9:獲得一個TransformerFactory對象
TransformerFactory transformerFactory = TransformerFactory.newInstance();
//step10:獲得一個Transformer對象
Transformer transformer = transformerFactory.newTransformer();
//step11:把document對象用一個DOMSource對象包裝起來
Source xmlSource = new DOMSource(document);
System.out.println(xmlSource);
//step12:建立一個存儲目標對象
Result outputTarget = new StreamResult(new File("C:\\Users\\yc\\Desktop\\persons.xml"));
//step13:生成相應的xml文件
transformer.transform(xmlSource,outputTarget);
}
}