小试dom对xml的操作

dom对xml的操作:
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.*;  
import java.io.*;
import org.w3c.dom.*;

public class control implements java.io.Serializable {
   private static String xmlStr="";
   private static int index=3;
   //private static final String PATH="file:///";
    
   public control() {
   }

   public String getString(){
        return xmlStr;
   }

   public static Document getDocument(String filename) throws Exception {
       xmlStr="";
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // 设定解析的叁数
        dbf.setIgnoringComments(true);
        dbf.setIgnoringElementContentWhitespace(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        //导入XML文件
        Document doc = db.parse(filename);
        return doc;
   }
    
   public int addElement(Node node,String name,String sex,String age, String tel){

             
             Element oRoot=((Document)node).getDocumentElement();
                         
             Element ename =((Document)node).createElement("name");  
             Text tname =((Document)node).createTextNode(name); 
             ename.appendChild(tname); 

             Element esex = ((Document)node).createElement("sex");  
             Text tsex = ((Document)node).createTextNode(sex); 
             esex.appendChild(tsex); 
          
             Element eage = ((Document)node).createElement("age");  
             Text tage = ((Document)node).createTextNode(age); 
             eage.appendChild(tage); 
            
             Element etel = ((Document)node).createElement("tel");  
             Text ttel  = ((Document)node).createTextNode(tel); 
             etel.appendChild(ttel);
     
             Element stu  =((Document)node).createElement("student"); 
             stu.setAttribute("id",Integer.toString(index));
             index++;
             stu.appendChild(ename);
                      stu.appendChild(esex);
                      stu.appendChild(eage);
                      stu.appendChild(etel);
            
             oRoot.appendChild(stu); 
             save((Document)node);
             if(stu==null) return 0;
             return 1;
   }
     
   public void traverseTree(Node node) throws Exception {
         if(node == null) {
            return;
         }
         int type = node.getNodeType();

         switch (type) {

            // handle document nodes
            case Node.DOCUMENT_NODE: {
               xmlStr+="<tr>";
               traverseTree(((Document)node).getDocumentElement());
               break;
            }

            // handle element nodes
            case Node.ELEMENT_NODE: {
               String elementName = node.getNodeName();
               if(elementName.equals("student")) {
                 xmlStr+="</tr><tr>";
               }
               NodeList childNodes =node.getChildNodes();
               if(childNodes != null) {
                  int length = childNodes.getLength();
                  for (int loopIndex = 0; loopIndex <length ; loopIndex++)
                  {
                     traverseTree(childNodes.item(loopIndex));
                  }
               }
               break;
            }
            
            // handle text nodes
            case Node.TEXT_NODE: {
               String data = node.getNodeValue().trim();
               if((data.indexOf(" ")  <0) && (data.length()> 0)) {
                 xmlStr+="<td>"+data+"</td>";
               }
            }
         }
    }
        //增加的保存操作
        private void save(Document doc){
            try{
                TransformerFactory tFactory =TransformerFactory.newInstance();
                Transformer transformer = tFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new java.io.File("ok.xml"));
                transformer.transform(source, result); 
            }catch(TransformerConfigurationException e)
        {
            e.printStackTrace();
        }catch(TransformerException e)
        {
           e.printStackTrace();
        }

        }
        
  public static void main(String []args){
            control ctrl = new control();
            try{
            Document doc = ctrl.getDocument("ok.xml");
            String name = "haha";
            String sex = "female";
            String age = "22";
            String tel = "23256";
            
           int i=ctrl.addElement(doc,name,sex,age,tel);
           Element oRoot=(doc).getDocumentElement();
           ctrl.traverseTree(oRoot);
           String str = ctrl.getString();
           System.out.println(str);
           
       }catch(Exception e){
        e.printStackTrace();
       }
        }
}
 

你可能感兴趣的:(xml)