`

java操作XML文件 dom 篇

阅读更多

我们需要引入的包:

import java.io.*;
import javax.xml.transform.*;    
import javax.xml.transform.dom.DOMSource;    
import javax.xml.transform.stream.StreamResult;        
import javax.xml.parsers.*;    
import org.w3c.dom.*;
import org.xml.sax.InputSource;

1、XML文件的内容转化为String

   /**
     * doc2String
     * xml文档内容转为String
     * @return 字符串
     * @param document
     */

   public static String doc2String(Document document)
    {
      String s = "";
      try
       {
           TransformerFactory tFactory = TransformerFactory.newInstance();    
           Transformer transformer = tFactory.newTransformer();
          /** 使用GB2312编码 */
          //transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
           Source source = new DOMSource( document );             
          /** 直接输出到控制台 */
          //Result output = new StreamResult( System.out );          
           StringWriter out = new StringWriter();  
           Result output = new StreamResult( out );
           transformer.transform( source, output );
           out.flush();
           s = out.toString();
       }catch(Exception ex)
       {             
           ex.printStackTrace();
       }       
      return s;
    }

2、符合XML格式的String 转化为XML Document

   /**
     * string2Document
     * 字符串转为Document
     * @return  
     * @param s xml格式的字符串
     */

   public static Document string2Document(String s)
    {
       Document document = null;
      try
       {
           DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
           document = parser.parse( new InputSource(new StringReader(s)) );
       }catch(Exception ex)
       {             
            ex.printStackTrace();
       }
      return document;
    }

3、Document对象保存为一个xml文件到本地

   /**
     * doc2XmlFile
     * Document对象保存为一个xml文件到本地
     * @return true:保存成功   flase:失败
     * @param filename 保存的文件名
     * @param document 需要保存的document对象
     */

   public static boolean doc2XmlFile(Document document,String filename)
    {
      boolean flag = true;
      try
       {
            /** document中的内容写入文件中   */
             TransformerFactory tFactory = TransformerFactory.newInstance();    
             Transformer transformer = tFactory.newTransformer();  
            /** 编码 */
            //transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
             DOMSource source = new DOMSource(document);  
             StreamResult result = new StreamResult(new File(filename));    
             transformer.transform(source, result);  
         }catch(Exception ex)
         {
             flag = false;
             ex.printStackTrace();
         }
        return flag;       
    }

4、xml格式的字符串保存为本地文件,如果字符串格式不符合xml规则,则返回失败

   /**
     * string2XmlFile
     * xml格式的字符串保存为本地文件,如果字符串格式不符合xml规则,则返回失败
     * @return true:保存成功   flase:失败
     * @param filename 保存的文件名
     * @param str 需要保存的字符串
     */

   public static boolean string2XmlFile(String str,String filename)
    {
      boolean flag = true;
      /* 以下格式生成的文件是以UTF-8为格式 */
      try
       {
          Document doc = string2Document(str);        
          flag = doc2XmlFile(doc,filename);
       }catch (Exception ex)
       {
          flag = false;
          ex.printStackTrace();
       }
      /** 以下不通过xml格式验证,象生成普通文件格式的方法生成xml文件
         OutputStream os = null;        
         try {
                 os = new FileOutputStream(filename);
                 os.write(str.getBytes());
                 os.flush();
         } catch (Exception ex) {
                 flag = false;
                 ex.printStackTrace();
         }finally
         {      
               try{  
                 if (os!=null) os.close();
               }catch (Exception ex) {
                 ex.printStackTrace();
               }               
         }
          */

      return flag;
    }

5、载入一个xml文档

   /**
     * load
     * 载入一个xml文档
     * @return 成功返回Document对象,失败返回null
     * @param uri 文件路径
     */

   public static Document load(String filename)
    {
       Document document = null;
      try  
       {  
            DocumentBuilderFactory   factory = DocumentBuilderFactory.newInstance();    
            DocumentBuilder builder=factory.newDocumentBuilder();    
            document=builder.parse(new File(filename));    
            document.normalize();
       }
      catch (Exception ex){
           ex.printStackTrace();
       }   
      return document;
    }

6、演示String保存为xml文件

   /**
     * xmlWriteDemoByString
     * 演示String保存为xml文件
     */

   public void xmlWriteDemoByString()
    {
      String s = "";
      /** xml格式标题 "<?xml version='1.0' encoding='GB2312'?>" 可以不用写*/
       s = "<?xml version='1.0' encoding='GB2312'?>"
          +"<config>\r\n"
          +"    <ftp name='DongDian'>\r\n"
          +"      <ftp-host>127.0.0.1</ftp-host>\r\n"
          +"      <ftp-port>21</ftp-port>\r\n"
          +"      <ftp-user>cxl</ftp-user>\r\n"
          +"      <ftp-pwd>longshine</ftp-pwd>\r\n"
          +"      <!-- ftp最多尝试连接次数 -->\r\n"
          +"      <ftp-try>50</ftp-try>\r\n"
          +"      <!-- ftp尝试连接延迟时间 -->\r\n"
          +"      <ftp-delay>10</ftp-delay>\r\n"
          +"      <ftp-chn>中文</ftp-chn>\r\n"
          +"   </ftp>\r\n"
          +"</config>\r\n";
      //文件生成到classes文件夹所在的目录里    
       string2XmlFile(s,"xmlWriteDemoByString.xml");    
      //文件生成到classes文件夹里    
       string2XmlFile(s,"classes/xmlWriteDemoByString.xml");   
    }

7、演示手动创建一个Document,并保存为XML文件

   /**
     * 演示手动创建一个Document,并保存为XML文件
     */

   public void xmlWriteDemoByDocument()
    {
        /** 建立document对象 */
        try  
         {  
            DocumentBuilderFactory   factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            Document document = builder.newDocument();
           /** 建立config根节点 */
            Element configElement = document.createElement("config");
            document.appendChild( configElement );
           /** 建立ftp节点 */
            Comment cmt = document.createComment("东电ftp配置");         
            configElement.appendChild(cmt);         
        
            Element ftpElement = document.createElement("ftp");
            configElement.appendChild(ftpElement);
            ftpElement.setAttribute("name","DongDian");
           /** ftp 属性配置 */
            Element element = document.createElement("ftp-host");
            element.appendChild(document.createTextNode( "127.0.0.1" ));
            ftpElement.appendChild(element);
            
            element = document.createElement("ftp-port");
            element.appendChild(document.createTextNode( "21" ));
            ftpElement.appendChild(element);
            
            element = document.createElement("ftp-user");
            element.appendChild(document.createTextNode( "cxl" ));
            ftpElement.appendChild(element);
            
            element = document.createElement("ftp-pwd");
            element.appendChild(document.createTextNode( "longshine" ));
            ftpElement.appendChild(element);
            
            element = document.createElement("ftp-try");
            element.appendChild(document.createTextNode( "50" ));
            ftpElement.appendChild(element);
            
            element = document.createElement("ftp-chn");
            element.appendChild(document.createTextNode( "中文" ));
            ftpElement.appendChild(element);
            
           /** 保存Document */
            doc2XmlFile(document,"classes/xmlWriteDemoByDocument.xml");
       }
      catch (Exception ex){
           ex.printStackTrace();
       }        
    }

8、演示读取文件的具体某个节点的值

   /**
     *   演示读取文件的具体某个节点的值  
     */

   public static void xmlReadDemo()
    {
       Document document = load("classes/xmlWriteDemoByDocument.xml");
       Node root=document.getDocumentElement();
      /** 如果root有子元素 */
      if(root.hasChildNodes())
       {
         /** ftpnodes */
          NodeList ftpnodes = root.getChildNodes();
         /** 循环取得ftp所有节点 */
         for (int i=0;i<ftpnodes.getLength();i++)
          {
             NodeList ftplist = ftpnodes.item(i).getChildNodes();
            for (int k=0;k<ftplist.getLength();k++)
             {
               Node subnode = ftplist.item(k);
              if (subnode.getNodeType()==Node.ELEMENT_NODE)
               {
                /** 打印ftp所有节点属性的值 */
                 System.out.println(subnode.getNodeName()+":"+subnode.getFirstChild().getNodeValue());
               }
             }
          }
       }
    }

9、演示修改文件的具体某个节点的值

   /**
     *   演示修改文件的具体某个节点的值  
     */

   public static void xmlUpdateDemo()
    {
       Document document = load("classes/xmlWriteDemoByDocument.xml");
       Node root=document.getDocumentElement();
      /** 如果root有子元素 */
      if(root.hasChildNodes())
       {
         /** ftpnodes */
          NodeList ftpnodes = root.getChildNodes();
         /** 循环取得ftp所有节点 */
         for (int i=0;i<ftpnodes.getLength();i++)
          {                       
             NodeList ftplist = ftpnodes.item(i).getChildNodes();
            for (int k=0;k<ftplist.getLength();k++)
             {
               Node subnode = ftplist.item(k);
              /** 删除ftp-chn节点 */
              if (subnode.getNodeType()==Node.ELEMENT_NODE&&subnode.getNodeName()=="ftp-chn")
               {
                  ftpnodes.item(i).removeChild(subnode);
               }
              /** 修改ftp-host的值为 192.168.0.1 */
              if (subnode.getNodeType()==Node.ELEMENT_NODE&&subnode.getNodeName()=="ftp-host")
               {                  
                  subnode.getFirstChild().setNodeValue("192.168.0.1");
               }
             }
             
          }
       }
      /** 修改完后重新保存 */
       doc2XmlFile(document,"classes/xmlWriteDemoByDocument.xml");
    }

----------------------JoeCom 2006-11-12

9.   xml 文件换成 xml格式的字符串

 

public String xmltoString(Document doc) {
  String xmlstring = null;// 储存字符串类型的xml文件

  if (doc != null) {
   StringWriter strWtr = new StringWriter();
   StreamResult strResult = new StreamResult(strWtr);
   TransformerFactory tfac = TransformerFactory.newInstance();
   try {
    Transformer t = tfac.newTransformer();
    t.setOutputProperty(OutputKeys.ENCODING, "gb2312");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html,//
    // text
    t.setOutputProperty(
      "{http://xml.apache.org/xslt}indent-amount", "4");
    t.transform(new DOMSource(((org.w3c.dom.Document) doc)
      .getDocumentElement()), strResult);
   } catch (Exception e) {
    System.err.println("XML.toString(Document): " + e);
   }
   xmlstring = strResult.getWriter().toString();

  }
  return xmlstring;
 }

 

 

 

分享到:
评论
1 楼 maimode 2012-02-07  
好东西,非常实用

相关推荐

Global site tag (gtag.js) - Google Analytics