posts - 2, comments - 1, trackbacks - 0, articles - 9
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

DOM:write xml

Posted on 2006-11-30 14:40 ljf2999 阅读(165) 评论(0)  编辑  收藏 所属分类: JDOM.DOM
 1 import  org.w3c.dom. * ;
 2 import  javax.xml.parsers. * ;
 3 import  javax.xml.transform. * ;
 4 import  javax.xml.transform.dom.DOMSource;
 5 import  javax.xml.transform.stream.StreamResult;
 6 import  java.io. * ;
 7 public   class  writexml  {
 8      private  Document document;
 9      private  String filename;
10     
11      public  writexml(String name)  throws  ParserConfigurationException {
12         filename = name;
13         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
14         DocumentBuilder builder = factory.newDocumentBuilder();
15         document = builder.newDocument();
16     }

17      public   void  toWrite(String mytitle,String mycontent) {
18         Element root = document.createElement( " WorkShop " );
19         document.appendChild(root);
20         Element title = document.createElement( " Title " );
21         title.appendChild(document.createTextNode(mytitle));
22         root.appendChild(title);
23         Element content = document.createElement( " Content " );
24         content.appendChild(document.createTextNode(mycontent));
25         root.appendChild(content);
26     }

27      public   void  toSave() {
28          try {
29             TransformerFactory tf = TransformerFactory.newInstance();
30             Transformer transformer = tf.newTransformer();
31             DOMSource source = new  DOMSource(document);
32             transformer.setOutputProperty(OutputKeys.ENCODING, " GB2312 " );
33             transformer.setOutputProperty(OutputKeys.INDENT, " yes " );
34             PrintWriter pw = new  PrintWriter( new  FileOutputStream(filename));
35             StreamResult result = new  StreamResult(pw);
36             transformer.transform(source,result);
37         }
  catch (TransformerException mye) {
38             mye.printStackTrace();
39         }
  catch (IOException exp) {
40             exp.printStackTrace();
41         }

42     }

43      public   static   void  main(String args[]) {
44          try {
45             writexml myxml = new  writexml( " d:\\training\\myxx\\src\\xml\\9.xml " );
46             myxml.toWrite( " ???? " , " ???? " );
47             myxml.toSave();
48             System.out.print( " Your writing is successful. " );
49         }
  catch (ParserConfigurationException exp) {
50             exp.printStackTrace();
51             System.out.print( " Your writing is failed. " );
52         }

53     }

54 }

55

只有注册用户登录后才能发表评论。


网站导航: