package com.xmlpull;
import java.io.File;
import java.io.FileOutputStream;
import org.kxml2.io.KXmlSerializer;
import org.xmlpull.v1.XmlSerializer;
/**
* <pre>
* xmlpull方式创建xml
* </pre>
* @author scott
*
*/
public class XmlPullCreateXML {
public static void main(String[] args) throws Exception{
XmlSerializer xmlSerializer=new KXmlSerializer();
xmlSerializer.setOutput(new FileOutputStream(new File("D:\\workspace\\demo\\src\\students.xml")), "utf-8");
xmlSerializer.startDocument(null, true);
xmlSerializer.startTag(null, "data");
for (int i = 0; i < 10; i++) {
xmlSerializer.startTag(null, "student");
xmlSerializer.attribute(null, "id", ""+(i+1));
xmlSerializer.startTag(null, "name");
xmlSerializer.text("student"+i);
xmlSerializer.endTag(null, "name");
xmlSerializer.startTag(null, "age");
xmlSerializer.text((i+10)+"");
xmlSerializer.endTag(null, "age");
xmlSerializer.startTag(null, "sex");
if(i%2==0){
xmlSerializer.text("女");
}else{
xmlSerializer.text("男");
}
xmlSerializer.endTag(null, "sex");
xmlSerializer.startTag(null, "address");
xmlSerializer.text("陕西西安");
xmlSerializer.endTag(null, "address");
xmlSerializer.endTag(null, "student");
}
xmlSerializer.endTag(null, "data");
xmlSerializer.endDocument();
xmlSerializer.flush();
}
}
生成的xml文件
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<data>
<student id="1">
<name>student0</name>
<age>10</age>
<sex>女</sex>
<address>陕西西安</address>
</student>
<student id="2">
<name>student1</name>
<age>11</age>
<sex>男</sex>
<address>陕西西安</address>
</student>
<student id="3">
<name>student2</name>
<age>12</age>
<sex>女</sex>
<address>陕西西安</address>
</student>
<student id="4">
<name>student3</name>
<age>13</age>
<sex>男</sex>
<address>陕西西安</address>
</student>
<student id="5">
<name>student4</name>
<age>14</age>
<sex>女</sex>
<address>陕西西安</address>
</student>
<student id="6">
<name>student5</name>
<age>15</age>
<sex>男</sex>
<address>陕西西安</address>
</student>
<student id="7">
<name>student6</name>
<age>16</age>
<sex>女</sex>
<address>陕西西安</address>
</student>
<student id="8">
<name>student7</name>
<age>17</age>
<sex>男</sex>
<address>陕西西安</address>
</student>
<student id="9">
<name>student8</name>
<age>18</age>
<sex>女</sex>
<address>陕西西安</address>
</student>
<student id="10">
<name>student9</name>
<age>19</age>
<sex>男</sex>
<address>陕西西安</address>
</student>
</data>