import java.awt.*;
import java.awt.event.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
class testDom {
String name,phone;
public testDom(String str1,String str2){
this.name=str1;
this.phone=str2;
}
public void go(){
try{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
DOMImplementation dom=db.getDOMImplementation();
DocumentType dt=dom.createDocumentType("联系方式","联系方式.dtd",null);
Document doc=dom.createDocument(null,"联系方式",dt);
//Attr at=doc.createAttribute("ID");
Text nm=doc.createTextNode(name);
Text tl=doc.createTextNode(phone);
Node root=doc.getDocumentElement();
Element first=doc.createElement("姓名");
first.setAttribute("ID","1");
first.appendChild(nm);
Element second=doc.createElement("电话");
second.setAttribute("宿舍电话","63114239");
second.appendChild(tl);
root.appendChild(first);
root.appendChild(second);
TransformerFactory tff=TransformerFactory.newInstance();
Transformer trans=tff.newTransformer();
DOMSource ds=new DOMSource(doc);
StreamResult sr=new StreamResult("联系方式.xml");
trans.transform(ds,sr);
}catch(Exception e){
e.printStackTrace();
}
}
}
public class testDom1 extends Frame implements ActionListener{
TextField tf1,tf2;
Label lb1,lb2;
Panel p1,p2,p3;
Button b;
String name,phone;
public testDom1(){
super("联系方式");
this.setLayout(new FlowLayout());
this.setSize(200,200);
b=new Button("提交");
b.addActionListener(this);
p1=new Panel();
p2=new Panel();
p3=new Panel();
tf1=new TextField(15);
tf2=new TextField(15);
lb1=new Label("姓名");
lb2=new Label("电话");
p1.add(lb1);
p1.add(tf1);
p2.add(lb2);
p2.add(tf2);
p3.add(b);
this.add(p1);
this.add(p2);
this.add(p3);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b){
name=tf1.getText().trim();
phone=tf2.getText().trim();
testDom td=new testDom(name,phone);
td.go();
}
}
public static void main(String []args){
testDom1 td1=new testDom1();
td1.pack();
td1.show();
}
}