java讀/寫XML

來源:互聯網
上載者:User

import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

 

 

 

/**
     *擷取配置密碼XML
     * @param attrName
     * @return
     */
    protected String getStandardPwd(String attrName) {
        if (e == null) {
            try {
                ServletContext s = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();//擷取伺服器路徑
                File f = new File(s.getRealPath("/") + "resources" + File.separatorChar + "useconfig.xml");//擷取XML檔案路徑
                SAXBuilder sb = new SAXBuilder();
                Document doc = sb.build(f);//
                e = doc.getRootElement().getChild("userconfig");//擷取根節(getRootElement)點下的PureFtpd(getChild)子節點
            } catch (Exception ex) {
                return null;
            }
        }
        return e.getChild(attrName).getAttribute("value").getValue();//擷取結點的屬性值
    }

    /**
     * 寫XML檔案
     * @param attrName
     */
    protected void setStandardPwd(String attrName, String randNumber) {

        try {
            ServletContext s = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
            String path = s.getRealPath("/") + "resources" + File.separatorChar + "useconfig.xml";//擷取XML檔案路徑
            FileInputStream fi = new FileInputStream(path);//將檔案寫入流
            SAXBuilder sb = new SAXBuilder();
            Document doc = sb.build(fi);//
            e = doc.getRootElement().getChild("userconfig");//擷取根節(getRootElement)點下的PureFtpd(getChild)子節點
            e.getChild(attrName).getAttribute("value").setValue(randNumber);//將屬性設定為隨機數
            FileOutputStream fz = null;
            String indent = " ";
            boolean newLines = true;
            XMLOutputter outp = new XMLOutputter(indent, newLines, "GBK");
            fz = new FileOutputStream(path);//輸出資料流
            outp.output(doc, fz);//儲存XML檔案修改
            fi.close();
            fz.close();

        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.