先定义一个简单的input.xml结构,让java进行input.xml的读取和重新输出为output.xml
input.xml格式:
<?xml version="1.0" encoding="gb2312"?>
<学生花名册>
<学生>
<姓名>李丽</姓名>
<性别>女</性别>
</学生>
<学生>
<姓名>刘畅</姓名>
<性别>男</性别>
</学生>
</学生花名册>
为标记我们定义相关的studentBean:
public class StudentBean {
private String sex;
private String name;
public void setSex(String s){sex=s;}
public String getSex(){return sex;}
public void setName(String n){name=n;}
public String getName(){return name;}
}
我们定义一个XMLTest类,包含2个操作,一个读取xml,一个写xml文件,并实现测试main函数。
package test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
public class XMLTest {
private Vector student_vector;
public XMLTest()
{
if(student_vector==null)
{
student_vector=new Vector();
}
}
public void readXMLFile(String location)
{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=null;
try{
db=dbf.newDocumentBuilder();
}catch(ParserConfigurationException pce)
{
System.err.println(pce);
System.exit(1);
}
Document doc=null;
try{
doc=db.parse(location);
}catch(Exception e)
{
System.err.println(e);
System.exit(1);
}
Element root=doc.getDocumentElement(); //root为"学生印花名"节点
NodeList students=root.getElementsByTagName("学生"); //返回“学生”节点集合
//为每一个读入的学生信息建立对应的studentBean对象,设置对象信息
for(int i=0;i<students.getLength();i++)
{
Element student=(Element)students.item(i);
StudentBean studentBean=new StudentBean();
//这里实现不是很合理,java的nodelist没有根据tag寻找子节点的方法,以后完善
studentBean.setName(student.getChildNodes().item(1).getTextContent());
//item(3)得到的是学生的性别节点,java把</姓名>也作为了一个子节点处理
studentBean.setSex(student.getChildNodes().item(3).getTextContent());
//保存学生对象到vector容器中
student_vector.add(studentBean);
}
}
//进行document操作首先实例化documentbuilderfactory,然后实例化documentbuilder,最后根据它得到document
public void writeXMLFile(String outFile)//throws Exception
{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=null;
try{
db=dbf.newDocumentBuilder();
}catch(Exception pce){
System.err.println(pce);
System.exit(1);
}
Document doc=db.newDocument();
//在doc中创建"学生花名册"tag作为根节点
Element root=doc.createElement("学生花名册");
doc.appendChild(root);
for(int i=0;i<student_vector.size();i++)
{
StudentBean student=(StudentBean)student_vector.get(i);
Element studentNode=doc.createElement("学生");
root.appendChild(studentNode);
//studentNode.setAttribute("姓名", student.getName());
//studentNode.setAttribute("性别", student.getSex());
Element stuNameNode=doc.createElement("姓名");
stuNameNode.appendChild(doc.createTextNode(student.getName()));
studentNode.appendChild(stuNameNode);
Element stuSexNode=doc.createElement("性别");
stuSexNode.appendChild(doc.createTextNode(student.getSex()));
studentNode.appendChild(stuSexNode);
}
//用xmlserializer把document的内容进行串化
FileOutputStream os=null;
try{
OutputFormat outformat=new OutputFormat(doc);
os=new FileOutputStream("output.xml");
XMLSerializer xmlSerilizer=new XMLSerializer(os,outformat);
xmlSerilizer.serialize(doc);
}catch(Exception e)
{
System.out.println("create xml failed...\n");
}
//功能同xmlSerializer,最后运行效果相同
/*
FileOutputStream outStream=null;
try{
outStream=new FileOutputStream(outFile);
}catch(Exception e)
{
System.err.println(e);
System.exit(1);
}
OutputStreamWriter outWriter=new OutputStreamWriter(outStream);
//doc.write(outWriter,"GB2312");
callWriteXMLFile(doc,outWriter,"GB2312");
try{
outWriter.close();
outStream.close();
}catch(Exception e)
{
System.err.println(e);
System.exit(1);
}
}
private void callWriteXMLFile(Document doc,OutputStreamWriter w,String encoding)
{
try{
Source source=new DOMSource(doc);
Result ret=new StreamResult(w);
Transformer xformer=TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.ENCODING,encoding);
xformer.transform(source,ret);
}catch(TransformerConfigurationException e)
{
e.printStackTrace();
}
catch(TransformerException e)
{
e.printStackTrace();
}
}*/
}
public static void main(String[] args)
{
XMLTest xmlTest=new XMLTest();
System.out.println("开始读xml文件...");
xmlTest.readXMLFile("Input.xml");
System.out.println("读入完毕,开始写output.xml文件");
xmlTest.writeXMLFile("Output.xml");
System.out.println("写入完成");
}
}