java 生成xml数据
java源码如下:
1 package hello.entity;
2
3 import org.w3c.dom.Document;
4 import org.w3c.dom.Element;
5 import org.w3c.dom.Text;
6
7 import javax.xml.parsers.DocumentBuilder;
8 import javax.xml.parsers.DocumentBuilderFactory;
9 import javax.xml.transform.Transformer;
10 import javax.xml.transform.TransformerFactory;
11 import javax.xml.transform.dom.DOMSource;
12 import javax.xml.transform.stream.StreamResult;
13 import java.io.File;
14
15 /**
16 * Created by Administrator on 2016/4/25 0025.
17 */
18 public class CreateXml {
19 public static void main(String[] args) throws Exception {
20 //实例化解析器
21 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
22 DocumentBuilder builder = factory.newDocumentBuilder();
23 //创建Document对象
24 Document doc = builder.newDocument();
25
26 //创建XML文件所需的各种对象并序列化
27 Element root = doc.createElement("root");
28 Element name = doc.createElement("name");
29 Text nameText = doc.createTextNode("zs");
30
31 name.appendChild(nameText);
32 root.appendChild(name);
33 doc.appendChild(root);
34
35 name.setAttribute("id", "2");
36
37 doc2XmlFile(doc,"test.xml");
38
39 }
40
41 public static boolean doc2XmlFile(Document document, String filename) {
42 boolean flag = true;
43 try {
44 TransformerFactory tFactory = TransformerFactory.newInstance();
45 Transformer transformer = tFactory.newTransformer();
46 /** 编码 */
47 // transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
48 DOMSource source = new DOMSource(document);
49 StreamResult result = new StreamResult(new File(filename));
50 transformer.transform(source, result);
51 } catch (Exception ex) {
52 flag = false;
53 ex.printStackTrace();
54 }
55 return flag;
56 }
57 }
生成的xml文件如下;
1 <?xml version="1.0" encoding="UTF-8" standalone="no"?><root><name id="2">zs</name></root>
这样就能用java来写xml数据了,通过属性和等级来控制xml里的布局样式。
注意,我这里生成的新xml在项目的根目录下的位置。
鄙视'砖家'和'叫兽'